[英]Marshalling static const char* from C++ to C#
I have a piece of code and I would like to know if it is correct or not: 我有一段代码,我想知道它是否正确:
hello.cpp HELLO.CPP
static const char _someGlovalVar[] = "my persistant gloval variable";
const char* DLLInterfaceGetName()
{
return _someGlovalVar;
}
hello.h hello.h
DLL_EXPORT const char* DLLInterfaceGetName();
hello.cs 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. 将返回值更改为IntPtr而不是字符串。
[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: 然后,当您在C#代码中调用它时,将指针编组为C#字符串:
IntPtr cstr = DLLInterfaceGetName();
String str = Marshal.PtrToStringAnsi(cstr);
Also, double check you use the right calling convention on the DLLImport. 另外,请仔细检查您是否在DLLImport上使用正确的调用约定。 I had an issue because it uses StdCall by default, and I actually wanted Cdecl. 我有一个问题,因为它默认使用StdCall,我实际上想要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? 一个静态的const char []指针可能在代码部分,不是吗? Hopefully, .NET marshaller copies the data in the string to its own string. 希望.NET marshaller将字符串中的数据复制到自己的字符串中。 I'm not sure how the CPP side handles this either - is it possible that different compilers might produce vastly different outputs? 我不确定CPP方面如何处理这个问题 - 不同的编译器是否可能产生截然不同的输出?
And also, shouldn't you put a \\0
at the end of the string? 而且,你不应该在字符串的末尾放一个\\0
吗? How does the caller know how long the string is with just char[]
? 调用者如何知道字符串与char[]
有多长? I think that if it doesn't work for you, this is the reason. 我认为,如果它不适合你,这就是原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.