Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cgo - How to convert go string to LPCWSTR

Tags:

windows

go

cgo

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 <windows.h>
*/
import "C"
import "unsafe"

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 "syscall"

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.

like image 509
Martin Drlík Avatar asked Nov 29 '25 16:11

Martin Drlík


1 Answers

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

  • github.com/antonlahti/go-winapi
  • github.com/AllenDang/w32

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("WM_SETTEXT failed")
        }
        return nil
    }
like image 113
bzhu Avatar answered Dec 02 '25 06:12

bzhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!