PInvoke with void * versus structure with IntPtr

Suppose I have a function called

Myfunction(const void * x); 

My C # declaration may be

 MyFunction(IntPtr x); 

Is it functionally and technically equivalent

 struct MyStruct { IntPtr P; } MyFunction(MyStruct x); 

Or there will be a difference in how they are sorted.

I ask this because the library that I am calling is all void *, typedef'd for other names, and in C # I would like to get type safety, for what it's worth it.

+6
source share
1 answer

If your StructLayout is consistent, then it is really identical.

The easiest way to check this out for yourself is, of course, to try:

Create a C ++ Win32 DLL project:

 extern "C" { __declspec(dllexport) void MyFunction(const void* ptr) { // put a breakpoint and inspect } } 

Make a C # project:

  public struct Foo { public IntPtr x; } [DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)] public static extern void MyFunctionWithIntPtr(IntPtr x); [DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)] public static extern void MyFunctionWithStruct(Foo x); static void Main(string[] args) { IntPtr j = new IntPtr(10); var s = new Foo(); sx = new IntPtr(10); MyFunctionWithIntPtr(j); MyFunctionWithStruct(s); } 

In the debug settings, make sure that you select "Initial debugging".

You will see that both values ​​are 0xA.

Please note that if you use out / ref parameters for your IntPtr vs Struct, they will be different values.

+3
source

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


All Articles