将 const char* 字符串从非托管传递到托管
我有两个通信组件 - 一个是托管的,另一个是非托管的。托管需要从非托管实现检索字符串(相同的字符串或只是一个副本)。我尝试了以下代码。
// 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 的值不是预期的值。有谁知道我在这里做错了什么?任何建议都会非常有帮助。
I have two communicating components - one managed, the other unmanaged. The managed needs to retrieve a character string from the unmanaged implementation (the same string or just a copy). I tried the following code.
// 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);
But, the value of testStr is not what is expected. Does anyone know what I'm doing wrong here? Any suggestions would be really helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你很接近,但你必须使用 PtrToStringAnsi()。 Auto 使用系统默认值,即 Unicode。
You're close but you have to use PtrToStringAnsi(). Auto uses the system default which will be Unicode.
我建议这样做:
UnmanagedType.LPStr 适用于字符串和 System.Text.StringBuilder,也许还有其他(我只使用过这两个)。不过,我发现 StringBuilder 的工作更加一致。
有关详细信息,请参阅这篇 MSDN 文章关于各种字符串编组选项。
I'd suggest this, instead:
UnmanagedType.LPStr works with strings and System.Text.StringBuilder, and perhaps others (I only ever used those two). I've found StringBuilder to work more consistantly, though.
See this MSDN article for further information on the various string marshalling options.