Is there a way to send an array of SafeHandles to a native function from c#?

250 views Asked by At

I have a native (c++) function that takes an array of pointers to images as an argument. In my c# API a pointer to an image is kept as a SafeHandle. Now I want to send an array of SafeHandles to my function but then I get into the following error.

System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #2': Invalid managed/unmanaged type combination (Arrays of SafeHandles are not supported).

Simplified the code looks like this:

Native Side

int concatenate_images(Image **img_ref, Image **images)
{
 // Concatenate the images and put the result in img_ref[0]
}

Managed side

Note that the ImageHandle is derived from the SafeHandle

Image Concatenate(Image[] images)
{
 ImageHandle h = new ImageHandle(); 
 if (!concatenate_images(ref h, handles_array))
     throw new Exception("Failed concatenating images.");
 return new Image(h);
}

private static extern int concatenate_images(ref ImageHandle img_ref, [In, Out] ImageHandle [] images)

I can of course solve the problem by extracting the IntPtr from the SafeHandle and send an array of those objects to my native function. But as I understand it, then I would not have some of the extra safety provided by the SafeHande.

So, how should I send my object to my native function? Do I have to make an array of IntPtr or is there a better way?

0

There are 0 answers