[英]Pinning char[] on P/Invoke call
我有char缓冲区的对象池,并在P / Invoke调用中传递了此缓冲区。 在呼叫之前是否需要固定缓冲区?
第一种方法:
[DllImport("Name", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void SomeMeth(char[] text, int size);
public static string CallSomeMeth()
{
char[] buffer = CharBufferPool.Allocate();
SomeMeth(buffer, 4095);
string result = new string(buffer, 0, Array.IndexOf(buffer, '\0'));
CharBufferPool.Free(buffer);
return result;
}
第二种方法:
[DllImport("Name", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern void SomeMeth(char* text, int size);
public static unsafe string CallSomeMeth2()
{
char[] buffer = CharBufferPool.Allocate();
string result;
fixed (char* buff = buffer)
{
SomeMeth(buff, 4095);
result = new string(buffer, 0, Array.IndexOf(buffer, '\0'));
}
CharBufferPool.Free(buffer);
return result;
}
不,传递给PInvoke的引用类型有自动固定功能。
从https://msdn.microsoft.com/zh-cn/magazine/cc163910.aspx#S3 :
当运行时封送处理程序发现您的代码将对托管引用对象的引用传递给本机代码时,它将自动固定该对象。
所以第一种方法是可以的。
只要:
SomeMeth(buffer, 4095);
我确实认为在代码周围添加常量是错误的...
SomeMeth(buffer, buffer.Length);
要么
SomeMeth(buffer, buffer.Length - 1);
可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.