将const char *字符串从非托管传递到托管

时间:2010-10-08 18:16:18

标签: c# c++ interop pinvoke intptr

我有两个通信组件 - 一个是托管组件,另一个是非托管组件。托管需要从非托管实现中检索字符串(相同的字符串或只是副本)。我尝试了以下代码。

// Unmanaged code
const char* GetTestName(Test* test)
{
    return test->getName();
}

// Managed wrapper
[DllImport(DllName, EntryPoint = "GetTestName")]
public static extern IntPtr GetTestName(IntPtr testObj);

// API Invocation
IntPtr testName = GetTestName(test);
string testStr = Marshal.PtrToStringAuto(testName);

但是,testStr的价值并不是预期的。有谁知道我在这里做错了什么?任何建议都会非常有用。

2 个答案:

答案 0 :(得分:2)

你已经关闭,但你必须使用PtrToStringAnsi()。 Auto使用系统默认值,即Unicode。

答案 1 :(得分:1)

我建议这样做,而不是:

[DllImport(DllName, EntryPoint = "EntryPoint")]
[MarshalAs(UnmanagedType.LPStr)]
public static extern StringBuilder GetTestName(IntPtr testObj);

UnmanagedType.LPStr适用于字符串和System.Text.StringBuilder,也许还有其他人(我只使用过这两个)。不过,我发现StringBuilder工作更加一致。

有关各种字符串编组选项的详细信息,请参阅this MSDN article