简体   繁体   中英

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:

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:

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

we found:

FnRetInt worked ok, but FnRetString didn't. proc.Call return type is uintptr , how can we change it to the type we wanted (for exsample: char* or string)?

A uintptr is a Go type that represents a pointer. 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. So you could do something like

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

to get a *uint8 back.

Look at syscall.Getwd windows implementation 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;
  • the data is uint16s (Microsoft WCHARs), instead of 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;

But should give you enough clues.

Alex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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