为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Go 和 Swig 中使用 LPCWSTR?

如何在 Go 和 Swig 中使用 LPCWSTR?

Go
扬帆大鱼 2021-11-01 15:59:55
我正在尝试使用 Swig 在 Go 中使用 C 库。这是简化的代码,我知道我可以使用 cgo,但我需要在 Swig 中使用带有 LPCWSTR 参数的函数。我在https://github.com/AllenDang/w32/blob/c92a5d7c8fed59d96a94905c1a4070fdb79478c9/typedef.go上看到,LPCWSTR这相当于*uint16sosyscall.UTF16PtrFromString()似乎是我需要的,但是当我运行代码时出现异常。我想知道我是否应该使用SwigcptrLPCWSTR。测试库#include <windows.h>#include <stdio.h>#include "libtest.h"__stdcall void hello(const LPCWSTR s){    printf("hello: %ls\n", s);}测试文件#ifndef EXAMPLE_DLL_H#define EXAMPLE_DLL_H#include <windows.h>#ifdef __cplusplusextern "C" {#endif#ifdef BUILDING_EXAMPLE_DLL#define EXAMPLE_DLL __declspec(dllexport)#else#define EXAMPLE_DLL __declspec(dllimport)#endifvoid __stdcall EXAMPLE_DLL hello(const LPCWSTR s);#ifdef __cplusplus}#endif#endif我使用以下命令构建 lib 和 DLL:gcc -c -DBUILDING_EXAMPLE_DLL libtest.cgcc -shared -o libtest.dll libtest.o -Wl,--out-implib,libtest.amain.swig%module main%{#include "libtest.h"%}%include "windows.i"%include "libtest.h"main.gopackage mainimport (    "syscall"    "unsafe")func main() {    p, err := syscall.UTF16PtrFromString("test")    if err != nil {        panic(err)    }    Hello(SwigcptrLPCWSTR(unsafe.Pointer(p)))}
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

我怀疑您看到的问题是因为您传递给 SWIG 的是一个双指针,而不仅仅是一个指针,即wchar_t**而不是wchar_t*.


我认为这是因为您调用UTF16PtrFromStringwhich 获取 UTF16 字符串的地址,然后随后调用unsafe.Pointer(p)which 我认为再次获取其输入的地址。


从 go 源代码:


func UTF16PtrFromString(s string) (*uint16) {

    a := UTF16FromString(s)

    return &a[0]

}

所以我想如果你改为使用:


func main() {

    p, err := syscall.UTF16FromString("test") // Note the subtle change here

    if err != nil {

        panic(err)

    }

    Hello(SwigcptrLPCWSTR(unsafe.Pointer(p)))

}

它应该按预期工作。


查看完整回答
反对 回复 2021-11-01
  • 1 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信