简体   繁体   English

如何从用C / C ++编写的DLL中调用导出的函数,返回类型是char *还是string?

[英]How to invoke an exported function from DLL written in C/C++ which return type is char* or string?

We designed C/C++ DLL just like this: 我们设计了C / C ++ DLL,如下所示:

WIN32_DLL_EXPORT int FnRetInt(int i)
{
   ....
   return 32 ;
} 

WIN32_DLL_EXPORT char* FnRetString()
{
   return "THIS IS A TEST STRING" ;
}

when we invoke these two functions in Go by using syscall: 当我们使用系统调用在Go调用这两个函数时:

hd:=syscall.NewLazyDLL(dll_path)
proc:=hd.NewProc(dll_func_name)
ret:=proc.Call()

we found: 我们找到:

FnRetInt worked ok, but FnRetString didn't. FnRetInt运行正常,但FnRetString没有。 proc.Call return type is uintptr , how can we change it to the type we wanted (for exsample: char* or string)? proc.Call返回类型是uintptr ,我们如何将其更改为我们想要的类型(例如:char *或string)?

A uintptr is a Go type that represents a pointer. uintptr是表示指针的Go类型。 You can use the unsafe package and convert it to unsafe.Pointer , and then you can convert an unsafe.Pointer into any Go pointer type. 您可以使用unsafe包并将其转换为unsafe.Pointer ,然后您可以将unsafe.Pointer转换为任何Go指针类型。 So you could do something like 所以你可以做点什么

str := (*uint8)(unsafe.Pointer(ret))

to get a *uint8 back. 得到一个*uint8

Look at syscall.Getwd windows implementation http://code.google.com/p/go/source/browse/src/pkg/syscall/syscall_windows.go#323 . 查看syscall.Getwd windows实现http://code.google.com/p/go/source/browse/src/pkg/syscall/syscall_windows.go#323 It is different from your problem: 它与您的问题不同:

  • it passes buffer to the dll, instead of receiving it from dll; 它将缓冲区传递给dll,而不是从dll接收它;
  • the data is uint16s (Microsoft WCHARs), instead of uint8s; 数据是uint16s(Microsoft WCHAR),而不是uint8s;
  • GetCurrentDirectory tells us how long resulting string is going to be, while your example, probably, expects you to search for 0 at the end; GetCurrentDirectory告诉我们结果字符串的长度,而你的例子可能希望你在结尾搜索0;

But should give you enough clues. 但应该给你足够的线索。

Alex 亚历克斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM