C# 字符串编组和内存管理
假设我在库中导出了以下C++函数:C# 字符串编组和内存管理,c#,c++,pinvoke,marshalling,C#,C++,Pinvoke,Marshalling,假设我在库中导出了以下C++函数: void foo(const wchar_t* text); 以及使用该函数的C#代码: [DllImport("bla.dll")] static extern void foo([MarshalAs(UnmanagedType.LPWStr)] string text); void Bar() { string s = "hello"; foo(s); } 当我调用foo时,.net封送处理程序
void foo(const wchar_t* text);
以及使用该函数的C#代码:
[DllImport("bla.dll")]
static extern void foo([MarshalAs(UnmanagedType.LPWStr)] string text);
void Bar()
{
string s = "hello";
foo(s);
}
foo
时,.net封送处理程序是否复制字符串,或者指针是否指向s
的缓冲区foo
)里面文本
编组为:
UnmanagedType.LPWStr
UnmanagedType.BStr
UnmanagedType.LPWStr
UnmanagedType.BStr
IntPtr
,该函数指向您以适当方式分配给自己的某个内存(可能通过调用某些本机代码,可能通过使用AllocHGlobal
等)。指针需要由您或本机代码使用相同的机制手动释放
UnmanagedType.LPWStr
UnmanagedType.BStr
如果需要本机函数获得指针的所有权,则需要传入一个
IntPtr
,该函数指向您以适当方式分配给自己的某个内存(可能通过调用某些本机代码,可能通过使用AllocHGlobal
等)。指针需要由您或本机代码使用相同的机制手动释放。无副本,.net字符串与const wchar\u t*兼容。BSTR需要复制,封送处理程序会处理它并在调用后销毁副本。没有副本,.net字符串与const wchar\u t*兼容。BSTR需要复制,封送员会处理它并在调用后销毁副本。