doubomudichen0832 2017-07-27 07:38
浏览 993

GoLang将C.wchar_t转换为字符串

I am looking to convert a [32]C.wchar_t to a go string.

The array is defined as follows in the dll I am talking to:

typedef struct myStruct {
    WCHAR someString[32];
}

I am defining the struct in go as follows:

type myStruct struct {
    someString [32]C.wchar_t
}

I have a method in the dll:

DLLINTERFACE HRESULT __stdcall GetMyStruct (myStruct* ptrMyStruct);

This method will populate the someString field of myStruct.

I am calling the method like so (this is working correctly, I think, I have not been able to see the contents of someString):

func getMyStruct() (*myStruct, uintptr) {
    var getMyStruct = dll.MustFindProc("GetMyStruct")
    var args = new(myStruct)
    ret, _, _ := getMyStruct .Call(uintptr(unsafe.Pointer(args)))

    fmt.Printf("Return: %d
", (int)(ret))
    return args, ret
}

I need to convert someString to a go string. I have tried using "github.com/GeertJohan/cgo.wchar", but it does not have a method for converting []C.whar_t to go string.

Currently I'm not sure if my go struct is correct. I'm also not sure if I am initializing myStruct correctly before sending it to the dll.

Any help will be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • drr47973 2017-07-27 09:24
    关注

    On Windows, wchar_t is normally UTF-16 (little-endian). They don't normally start with a BOM (which is present so a decoder can detect if they are stored in big or little endian form).

    There is a utf16 package but this only translates individual runes. However, there is an additional unicode text encoding package that can help.

    You would probably do something like this:

    dec:=unicode.UTF16(unicode.LittleEndian,unicode.UseBOM).NewDecoder()
    out,err:= dec.Bytes(([]byte)(unsafe.Pointer(args.someString)))
    if err!=nil {
        //handle error
    }
    // Strings are null terminated, only want content up to null byte
    i:=bytes.IndexByte(out,0)
    if i==-1 {
       i = len(out)
    }
    s:=string(out[:i]) 
    

    However, I'd be tempted to declare someString as [64]byte which is the amount of bytes that a 32 character (16 bites = 2 bytes per character) would need. This would avoid the unsafe typecasting but otherwise should work as above.

    I'm doing this off the top of my head so the code above is meant as an example & may not necessarily work - use at your peril :-)

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度