[Mono-list] C to Mono interop passing a byte array

Jonathan Pryor jonpryor at vt.edu
Fri May 20 07:10:16 EDT 2011


On May 20, 2011, at 5:00 AM, Mike D wrote:
> I am trying to pass a byte array (image data) from C/Obj-C to managed
> using mono_runtime_invoke.  I can get a hold of the MonoMethod which
> has a byte[] as a parameter and I can call the method but when I try
> to use the byte[] in any way on the C# end I get an instant crash.
> Are there any examples out there of sending a byte[] or any other
> pointers on pulling this off?
> 
> NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]
> pathForResource:@"someImage.png" ofType:nil]];
> int size = data.length;			
> void *arg[2] = { (void*)data.bytes, &size };
> mono_runtime_invoke( method, NULL, args, NULL );

The problem is that your managed method wants a `byte[]`, which is a managed array, yet you're providing a C array. They are not the same.

You have two fixes:

 1. Don't use byte[], but instead use `byte*` (unsafe code) or IntPtr.
 2. In your native code, create a proper `byte[]` by using mono_array_new() and filling the byte[] with mono_array_set().

 - Jon



More information about the Mono-list mailing list