I have a piece of code and I would like to know if it is correct or not:
static const char _someGlovalVar = "my persistant gloval variable";
const char* DLLInterfaceGetName()
DLL_EXPORT const char* DLLInterfaceGetName();
[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.