如何在 Go 和 Swig 中使用 LPCWSTR?

我正在尝试使用 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 __cplusplus

extern "C" {

#endif


#ifdef BUILDING_EXAMPLE_DLL

#define EXAMPLE_DLL __declspec(dllexport)

#else

#define EXAMPLE_DLL __declspec(dllimport)

#endif


void __stdcall EXAMPLE_DLL hello(const LPCWSTR s);


#ifdef __cplusplus

}

#endif


#endif

我使用以下命令构建 lib 和 DLL:


gcc -c -DBUILDING_EXAMPLE_DLL libtest.c

gcc -shared -o libtest.dll libtest.o -Wl,--out-implib,libtest.a

main.swig


%module main


%{

#include "libtest.h"

%}


%include "windows.i"

%include "libtest.h"

main.go


package main


import (

    "syscall"

    "unsafe"

)


func main() {

    p, err := syscall.UTF16PtrFromString("test")

    if err != nil {

        panic(err)

    }

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

}


扬帆大鱼
浏览 204回答 1
1回答

一只斗牛犬

我怀疑您看到的问题是因为您传递给 SWIG 的是一个双指针,而不仅仅是一个指针,即wchar_t**而不是wchar_t*.我认为这是因为您调用UTF16PtrFromStringwhich 获取 UTF16 字符串的地址,然后随后调用unsafe.Pointer(p)which 我认为再次获取其输入的地址。从 go 源代码:func UTF16PtrFromString(s string) (*uint16) {&nbsp; &nbsp; a := UTF16FromString(s)&nbsp; &nbsp; return &a[0]}所以我想如果你改为使用:func main() {&nbsp; &nbsp; p, err := syscall.UTF16FromString("test") // Note the subtle change here&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; Hello(SwigcptrLPCWSTR(unsafe.Pointer(p)))}它应该按预期工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go