DLL Import malloc Double Indirect Pointers

I have a C function that takes multiple arguments of double indirect pointers.

something like that

int myFunction (int ** foo, int** bar, int **baz){ int size = figureOutSizeFunction(); *foo = (int*) malloc (sizeof(int) * size); return SomeOtherValue; } 

Now in C # I am trying to pass it a link to IntPtr, however IntPtr is always zero. And when I pass these values ​​to the next C DLL function, the DLL crashes with a system access violation. I know that the code only works in the C environment (I have a "main" one that checks the code), however it does not work when called from C #

What type of variable do I need in C # to go to C DLL? ref ref int?

+4
source share
1 answer

When working with double pointers ( ** ), the best way is to simply marshal them as IntPtr .

 public static extern int myFunction(IntPtr foo, IntPtr bar, IntPtr baz); 

Then digging into a double pointer in managed code is performed.

 IntPtr foo, bar baz; ... myFunction(foo, bar, baz); IntPtr oneDeep = (IntPtr)Marshal.PtrToStructure(foo, typeof(IntPtr)); int value = (int)Marshal.PtrToStructure(oneDeep, typeof(int)); 

The above code is obviously a bit ... ugly. I prefer to wrap it with nice extension methods on IntPtr .

 public static class Extensions { public static T Deref<T>(this IntPtr ptr) { return (T)Marshal.PtrToStructure(ptr, typeof(T)); } } 

Then the above can be rewritten as more readable

 int value = ptr.Deref<IntPtr>().Deref<int>(); 
+4
source

All Articles