cgo – 如何将Go字符串转换为LPCWSTR

huangapple go评论94阅读模式
英文:

cgo - How to convert go string to LPCWSTR

问题

package mypackage

/*
#cgo LDFLAGS: -luser32
#include <windows.h>
*/
import "C"
import "unsafe"

func MessageBox(m string) {
cm := C.CString(m)
defer C.free(unsafe.Pointer(cm))
C.MessageBoxA(C.HWND(nil), (*C.CHAR)(cm), C.LPCSTR(nil), 0) // It display a message.
}

import "syscall"

func MessageBoxU(m string) {
C.MessageBoxW(C.HWND(nil), (*C.WCHAR)(unsafe.Pointer(syscall.StringToUTF16Ptr(m))), C.LPCWSTR(nil), 0)
}

英文:

I would like to use some of windows api, but I have no idea how to start. Is there any tutorial for it?

Anyway I have a simple code. Can you please help me to get this correct?

package mypackage
/*
#cgo LDFLAGS: -luser32
#include &lt;windows.h&gt;
*/
import &quot;C&quot;
import &quot;unsafe&quot;

func MessageBox(m string) {
      cm := C.CString(s)
      defer C.free(unsafe.Pointer(cm))
      C.MessageBoxA(C.HWND(nil), (*C.CHAR)(cm), C.LPCSTR(nil), 0) // It display a message.
}

Edit: I can deal with char* but still do not know what with wchar_t*.

import &quot;syscall&quot;

func MessageBoxU(m string) {
        C.MessageBoxW(C.HWND(nil), (*C.WCHAR)(unsafe.Pointer(syscall.StringToUTF16Ptr(m))), C.LPCWSTR(nil), 0)
}

Please let me know if this is not go idiom.

答案1

得分: 5

以下是两个将Windows API封装为Go语言的项目:

一个使用示例:

    func setWidgetText(hwnd HWND, text string) error {
        if TRUE != go-winapi.SendMessage(hwnd, WM_SETTEXT, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text)))) {
            return newError("WM_SETTEXT failed")
        }
        return nil
    }
英文:

The following are two projects which wrap the Windows API to Go:

A usage example:

    func setWidgetText(hwnd HWND, text string) error {
        if TRUE != go-winapi.SendMessage(hwnd, WM_SETTEXT, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text)))) {
            return newError(&quot;WM_SETTEXT failed&quot;)
        }
        return nil
    }

huangapple
  • 本文由 发表于 2012年4月21日 22:24:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/10259742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定