Marshal [In] [Out] Attributes

I call an unmanaged function in my C # code.

The declaration of this function is as follows:

int myFun(unsigned char* inputBuffer, unsigned char* &outputBuffer); 

I use this function as follows:

 [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); 

Although I mentioned [InAttribute] for byte[] inputBuffer , the function still changed the values โ€‹โ€‹of a . The CLR seems to use its own default marshaling behavior. I used byte[] because it is the C # equivalent for unsigned char* .

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

I really appreciate your help. For more information, please read the msdn page .

+6
source share
1 answer

From the documentation with an accent:

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

Since byte is blittable, your byte array is pinned, not copied, and therefore marshaled as In / Out.

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

C # char not blittable . The char array is not pinned, so [In] char[] marshals as an In parameter.

+8
source

Source: https://habr.com/ru/post/988611/


All Articles