[Mono-list] PInvoke & Marshaling problem

Kai Reichert kai.reichert@udo.edu
Sat, 3 Jul 2004 23:06:33 +0200


I want to pass an array of bytes to a method compiled in c/c++.

The first naiv method works and looks like this : 

 - ---------------------
  xx.c :

void takeArray( unsigned char array[] ){
  /* do something useful with it */

  xy.cs :

  [ DllImport(myclib.so) ]
  static extern void takeArray(  byte[] array  );
  byte[] array = new byte[10];
  takeArray( array );
 - --------------------------
O.K., this one works perfectly.
But now consider you have a c-method that takes the array as

  takeArray( const void *pointer )
YES, it makes sense, e.g. the OpenGL method glTexImage2D.

Since all structures are passed by reference the parameter of the method is 
just the pointer to the beginning of the structure in memory. so I only need 
a way to access this pointer.

my aproach was the following : 

takeArray ( GCHandle.Alloc( array, 
GCHandleType.Pinned).AddrOfPinnedObject() );

BUT this method invocation is not associated with the right piece of memory 
that the subsequent c-method gets :-)

Yes I know that Mono has a garbage collection and there are mechanisms in the 
runtimes that copy memory from managed to unmanaged. This wouldn't be a 
problem ...

I just want to know why it is not possible to pass 

  System.IntPtr   --C-->  const void*
  byte[]    --C--> unsigned char array[]
works ;-)

Thx for reading boring PInvoke problems :-)