Do I need to do MarshalAs with primitive data types from unmanaged C++ dll in C#?

550 views Asked by At

I have a basic question,

I have a C++ unmanaged dll that have functions with parameters in and out some unsigned char,unsigned short,unsigned long,signed char,signed short, signed long data type.

Do I need to Marshal it or I can directly mapped it? What is the best practice if any?

e.g dll

unsigned long SomeFunc(unsigned char variableA);

C# (direct map in C#)

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern uint SomeFunc(byte variableA);
2

There are 2 answers

0
xanatos On

To expand on the response of mozfox, the list is: byte, sbyte, short, ushort, int, uint, long, ulong, IntPtr, UIntPtr, float, double, single-dimensional arrays ([]) of those, struct of those. Missing are bool (that can be marshaled in various ways), char (don't ask why... I don't know), string.

3
Mandar On

Most data types have a common representation in both managed and unmanaged memory and do not require special handling by the interop marshaler. These types are called blittable types because they do not require conversion when passed between managed and unmanaged code.

MSDN: https://learn.microsoft.com/en-us/dotnet/framework/interop/blittable-and-non-blittable-types