问题描述
我正在用我的C#代码调用一个非托管函数.
I'm invoking an unmanaged function in my C# code.
此函数的声明如下:
int myFun(unsigned char* inputBuffer, unsigned char* &outputBuffer);
我按如下方式使用此功能:
I use this function as follow:
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int myFun([In] byte[] inputBuffer, out IntPtr outputBuffer);
byte[] a = Encoding.ASCII.GetBytes("sampletext!");
IntPtr b;
res = myFun(a, out b);
尽管我提到了 byte [] inputBuffer
的 [InAttribute]
,但是该函数仍然更改了 a
的值.似乎CLR正在使用其自己的默认封送处理行为.我使用了 byte []
,因为它等效于 unsigned char *
的C#.
Although I mentioned [InAttribute]
for byte[] inputBuffer
, the function still changeds the values of a
. It seems that CLR is using its own default marshaling behavior.I used byte[]
because it is C# equivalent for unsigned char*
.
当我用 char []
替换 byte []
时,CLR将遵循我的In-Out属性.
When I substitite byte[]
with char[]
the CLR will follow my In-Out attributes.
非常感谢您的帮助.有关更多信息,请阅读此 msdn页面.
I highly appreciate your help.For more information please read this msdn page.
推荐答案
来自文档,我的重点是:
由于 byte
是可蓝调的,因此您的字节数组是固定的而不是被复制的,因此封送为In/Out.
Since byte
is blittable, your array of byte is pinned rather than copied, and so marshals as In/Out.
C#类型 char
是不可设置. char
的数组未固定,因此 [In] char []
封送为In参数.
The C# type char
is not blittable. An array of char
is not pinned, and so [In] char[]
marshals as an In parameter.
这篇关于元帅的[进] [出]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!