Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MarshalAs attribute case study

When should we use this attribute and why do we need it? For example, if the native function in c takes as a parameter a pointer to unsigned char, and I know that it's needed to fulfill the array of unsigned chars, why can't I use array of bytes in C# to use this function? Is it necessary to do marshalling?

like image 544
Sergey Avatar asked Jun 16 '11 03:06

Sergey


2 Answers

The runtime will be able to automatically determine how to marshal data between native and managed code in most cases, so you generally don't need to specify the attribute. MarshalAs is only necessary when there is an ambiguity in the definition (and you want to tell the runtime precisely how to marshal the data) or if you require non-default behaviour.

In my experience, MarshalAs is only really required when working with strings, since there are so many different representations in native code; unicode/ansi, c-strings or not, etc.

like image 78
Bradley Smith Avatar answered Oct 25 '22 05:10

Bradley Smith


Additional use of MarshalAs attribute is marshalling fixed-size arrays (including fixed-size strings) with ByValArray and SizeConst parameters. For example, many structures from Windows API contain fixed-size strings.

like image 21
Alex F Avatar answered Oct 25 '22 04:10

Alex F