tags:

views:

45

answers:

2

Hi,

I have exported the following C function to be invoked in a DLL file.

uint8_t* _stdcall GetCurrentImage();

Now I want to call this function in C# to get a bitmap Image. How can I do this?

Thanks in advance!

+2  A: 

You will need to know the exact number of bytes returned and the bitmap dimensions (height, width and encoding). Then you can declare it in C# as:

[DllImport("yourlib.dll")]
private static extern IntPtr GetCurrentImage();

The IntPtr you get from that can be used with Marshal.Copy, to get the raw bytes:

byte[]  buffer = new byte[length];
IntPtr beginPtr = GetCurrentImage();
Marshal.Copy(beginPtr, buffer,0,length);

Finally, declare a Bitmap with the dimensions of your image and the PixelFormat used (if it is a non-standard pixelformat, you might have to do some conversion yourself). Then you can copy the data into the raw bitmap bytes, by using LockBits to get a BitmapData instance that points to the raw bitmap data.

driis
And who is going to dispose of the memory allocated by `GetCurrentImage()`?
Timwi
@Timwi, of course that depends on the contract defined in the external DLL. Perhaps there is a function to do that already available, or perhaps it needs to be added. But of course the OP will need to take it into consideration. If the memory was allocated using LocalAlloc in unmanaged code, one can use the Marshal.FreeHGlobal in managed code to free it.
driis
A: 

The common strategy for things like this is to pass in a buffer and have the function fill the buffer. Otherwise you run into trouble with disposing of the memory allocated; in other words, you will have a memory leak.

So you should have C functions like this...

uint32_t _stdcall GetCurrentImageSize();
void _stdcall GetCurrentImage(uint8_t* buffer, int offset, int bufferSize);

And then in C# you would do something like...

var buffer = new byte [ GetCurrentImageSize() ];
fixed (byte* b = &buffer[0])
    GetCurrentImage(b, 0, buffer.Length);

// 'buffer' now contains the image
Timwi