问题描述:

I have a piece of code and I would like to know if it is correct or not:

hello.cpp

static const char _someGlovalVar[] = "my persistant gloval variable";

const char* DLLInterfaceGetName()

{

return _someGlovalVar;

}

hello.h

DLL_EXPORT const char* DLLInterfaceGetName();

hello.cs

[DllImport("hello.dll", EntryPoint = "DLLInterfaceGetName", CharSet = CharSet.Ansi)]

public static extern string DLLInterfaceGetName();

Is this correct?

网友答案:

Change your return value to IntPtr instead of string.

[DllImport("hello.dll", EntryPoint = "DLLInterfaceGetName", CharSet = CharSet.Ansi)]
public static extern IntPtr DLLInterfaceGetName();

Then when you call it in your C# code, marshall the pointer into a C# string:

IntPtr cstr = DLLInterfaceGetName();
String str = Marshal.PtrToStringAnsi(cstr);

Also, double check you use the right calling convention on the DLLImport. I had an issue because it uses StdCall by default, and I actually wanted Cdecl.

网友答案:

Does it work? In this case, I don't think you have to care about anything else :)

Although personally, I'm a bit worried about how this is handled. A static const char[] pointer is probably in the code section, isn't it? Hopefully, .NET marshaller copies the data in the string to its own string. I'm not sure how the CPP side handles this either - is it possible that different compilers might produce vastly different outputs?

And also, shouldn't you put a \0 at the end of the string? How does the caller know how long the string is with just char[]? I think that if it doesn't work for you, this is the reason.

相关阅读:
Top