[Mono-list] copying pointer data without unsafe code ?

Jonathan Pryor jonpryor@vt.edu
Thu, 30 Sep 2004 20:23:15 -0400


On Thu, 2004-09-30 at 13:37, Glenn Pierce wrote:
<snip/>
> The client C code would be:
> 
> void* buf;
> buf = malloc (bufsize);
> retval = GetImageData (buf, bufsize);
> 
> What I need is to get the image data into a managed array. 

Question 1: What *exactly* is your image data?  A void* doesn't tell me
much...

> Currently I am using unsafe code to get the data into a void pointer,
> with:
> 
> [DllImport(Library)]
> private unsafe extern static uint IcsGetData (void* dest, uint n);

This works.

> I tried experimenting with [Out] System.Array as I don't know the
> necessary image type
> until runtime and so I don't know the type of array. However, I had
> with no luck with this method.

The runtime has no way of knowing what you're dealing with, so using
System.Array won't help you.  However, you can overload:

	[DllImport(Library)]
	private static extern uint IcsGetData ([Out] byte[] data, uint n);

	[DllImport(Library)]
	private static extern uint IcsGetData ([Out] int[] data, uint n);

	[DllImport(Library)]
	private static extern uint IcsGetData ([Out] long[] data, uint n);

	[DllImport(Library)]
	private static extern uint IcsGetData ([Out] MyStruct[] data, uint n);

At least, I believe the above should work (I'm too lazy to actually test
right now.  Sorry.)

> After I have the pointer to the image data I then copy the data into a
> managed array
> by using code to allocate unmanaged memory as seen
> http://www.asprelated.com/csharp/sharp-18_8.aspx.

This works.

> Is there an easier way I can get the image data into a managed array
> without using unsafe code ?

I've given some prototypes above, so hopefully those will help you.

 - Jon