[Mono-list] P/Invoke IntPtr versus byte[]
Tim Rädisch
tim.raedisch@udo.edu
Sat, 3 Jul 2004 22:09:44 +0200
Hi!
Following scenario (it's very absract, because the real programm would be
needless complicated.
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] );
}
}
In C# I want to access the method with the following array
byte[] mdArray = new byte[64*64*3];
mdArray[1982] = 1;
Every element is 0, except 1982.
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?
Tim