元帅的[进] [出]属性 [英] Marshal's [In] [Out] Attributes

查看:56
本文介绍了元帅的[进] [出]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用我的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.

推荐答案

来自文档,我的重点是:

作为一种优化,仅包含 blittable 成员的 blittable 类型和类的数组在封送处理期间被固定而不是复制.当呼叫者和被呼叫者在同一套公寓中时,这些类型似乎被编组为In/Out参数.但是,这些类型实际上被编组为In参数,并且如果您想将参数编组为In/Out参数,则必须应用InAttribute和OutAttribute属性.

As an optimization, arrays of blittable types and classes that contain only blittable members are pinned instead of copied during marshaling. These types can appear to be marshaled as In/Out parameters when the caller and callee are in the same apartment. However, these types are actually marshaled as In parameters, and you must apply the InAttribute and OutAttribute attributes if you want to marshal the argument as an In/Out parameter.

由于 byte 是可蓝调的,因此您的字节数组是固定的而不是被复制的,因此封送为In/Out.

Since byte is blittable, your array of byte is pinned rather than copied, and so marshals as In/Out.

当我用char []替换byte []时,CLR将遵循我的In-Out属性.

When I substitute byte[] with char[] the CLR will follow my In-Out attributes.

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.

这篇关于元帅的[进] [出]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆