2

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);
drf
  • 8,461
  • 32
  • 50
nutcracker
  • 21
  • 1
  • It is not normally a problem that you specify an UnmanagedType that is already the default choice. But you did pick one where the default is not always U4. `long` is tricky in 64-bit mode, it is U4 on Windows but U8 on the unixes. If this code is going to have to be portable then you would favor modifying the C++ declaration. – Hans Passant May 28 '18 at 07:56
  • appreciate your comment. But I don't really get you. Can you provide link on or explain a bit more on this so that I can have better understanding. I really would like to know what is the best practice for this. – nutcracker May 30 '18 at 01:27

2 Answers2

2

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

Mandar
  • 1,006
  • 11
  • 28
  • Better if you link the newer version (https://msdn.microsoft.com/en-us/library/75dwhxf7(v=vs.100).aspx)... The older version forgot of `float`, and `double`. – xanatos May 28 '18 at 06:17
  • So, this line of code is sufficient enough? `[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern uint SomeFunc(byte variableA);` – nutcracker May 28 '18 at 06:57
  • @nutcracker If you are working in Windows, and the method is cdecl (it isn't marked as stdcall) then yes. – xanatos May 28 '18 at 07:20
0

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.

xanatos
  • 109,618
  • 12
  • 197
  • 280