[Mono-list] P/Invoke IntPtr versus byte[]

Paolo Molaro lupus@ximian.com
Mon, 5 Jul 2004 17:12:55 +0200


On 07/03/04 Tim Rädisch wrote:
> I want to acces the following C-methode by DllImport.
> 
> void multiDimArrayTest( const void* array ) {
>  int i;
>  unsigned char *mdarray = (unsigned char*)array;
> 
>  printf("%i %i\n", mdarray, array );
> 
>  printf ("size of array[x]: %i\n", sizeof(mdarray[0]) ) ;
>  for( i=0; i<64*64*3; i++){
>    if( mdarray[i] != 0 )
>      printf( "==> array(%i) = %i\n",i, mdarray[i] );
>  }
> }
[...]
> Because it is a "const void*" I used the following DllImport statement
>   [ DllImport(lib) ]
>   static extern void multiDimArrayTest( byte[] elems );
> and this methode call
>   multiDimArrayTest( GCHandle.Alloc( mdArray, 
> GCHandleType.Pinned).AddrOfPinnedObject() );
> 
> The output is:
> size of array[x]: 1
> ==> array(0) = 120
> ==> array(1) = 207
> ==> array(2) = 4
> ==> array(3) = 8
> ==> array(13) = 48
> ==> array(1998) = 1
> Except of 5 elements all are correct. But I don't know why elements 0,1,2,3 
> and 13 are wrong.
> 
> 
> If I use the following import and call
>   [ DllImport(lib) ]
>   static extern void multiDimArrayTest( byte[] elems );
> 
>   multiDimArrayTest( mdArray );
> the output is
> size of array[x]: 1
> ==> array(1982) = 1
> 
> and this one is correct.
> 
> 
> But I don't want to hard code the type, because it is not ever a byte-array. 
> Yes that is possible, it is C :D (not my C)
> 
> 
> 
> So, can someone explain me why IntPtr fails, and if there is another 
> alternative?

Our AddrOfPinnedObject() impl is broken, Marcus already filed a bug, so
it will be fixed by the next release. What you can do in the meantime is
to declare two (or more, as needed) versions of the pinvoke method:

   [ DllImport(lib) ]
   static extern void multiDimArrayTest( byte[] elems );

   [ DllImport(lib) ]
   static extern void multiDimArrayTest( double[] elems );

You'll always get the address of the first element in the C code, the C#
code is simpler and it's faster, too.

lupus

-- 
-----------------------------------------------------------------
lupus@debian.org                                     debian/rules
lupus@ximian.com                             Monkeys do it better