如何从 DLL 的导出函数中获取 std::string?

How to get in Go a std::string from an exported function of a DLL?

我想加载自定义 DLL(C++ 之一)并调用它导出的函数? 这是我的 Go 代码:

func main() {
    dllForGo := syscall.MustLoadDLL("dllForGo.dll")
    defer dllForGo.Release()
    getHello:= dllForGo.MustFindProc("getHello")
    r1, _, err := getHello.Call(0) // also tried with .Call() and still got the same error
}

这里是我的 DLL 的 C++ 代码:

 std::string __stdcall getHello(void) {
     int a = 1;
     double b = 10;
     return ("Hello-World !!"+std::to_string(a) + std::to_string(b));
}

我试图强制使用 __stdcall(为此 link 一个 .def 文件,因为我认为 __declspec(dllexport) 可能是个问题)。

但是,使用 DUMPBIN,我可以看到 getHello 使用 __cdecl 调用约定。这是个问题吗?

这是我在 运行 我的 Go 时遇到的错误:

Exception 0xc0000005 0x1 0x10 0x7fef0591327
PC=0x7fef0591327

syscall.Syscall(0x7fef05910d0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0)
    D:/Go/src/runtime/syscall_windows.go:172 +0xf9
syscall.(*Proc).Call(0xc00004e420, 0xc000058090, 0x1, 0x1, 0x565520, 0x21, 0x2e06a0, 0x0)
    D:/Go/src/syscall/dll_windows.go:146 +0x140
main.main()
    D:/GoLand_Projects/dllLoad/main.go:58 +0x335
rax     0x22fdb8
rbx     0x9
rcx     0x30
rdi     0x9
rsi     0x0
rbp     0x22fdd9
rsp     0x22fd60
r8      0x30303030302e3031
r9      0x7fef1220000
r10     0x22fd90
r11     0x771a1f
r12     0xa
r13     0x9
r14     0x0
r15     0x0
rip     0x7fef0591327
rflags  0x10202
cs      0x33
fs      0x53
gs      0x2b

编辑

其实getHello函数执行的很好。我将其修改为写入文件:

 std::string __stdcall  getHello(void) {
     std::ofstream outfile("D:\test123.txt");
     outfile << "getHello working!" << std::endl;
     outfile.close();
     int a = 1;
     double b = 10;
    return ("Hello-World !!"+std::to_string(a) + std::to_string(b));
}

...文件被写入。所以问题出在导出函数 returns 之后。 这让我觉得我需要将 Go 部分中的某些内容更改为 "welcome" returned std::string.

EDIT2

如果我把导出函数的return类型改成void那么,调用return无一例外。是否可以额外提示它确实与调用约定有关?

这是我从地鼠那里得到的答案:

working with objects is tricky. string is an object, it probably has a vtable somewhere, it also has an internal structure (although I forget what it is, my guess would be it's similar to a COM bstring or a go slice, maybe check the relevant c++ sources). Calling methods would involve finding the address of the dispatch table entires and calling those as functions. I suggest you start with a C char * and work your way to that.

所以我尝试将一个char ** 作为参数,我可以在DLL 函数中修改它并在Go 中显示修改。我还尝试返回一个基本类型 (int),它也有效。