Retrieving an unsigned char pointer out of C++ DLL in CSharp ?

T

Tom

Hi newsgroup,

I have read a lot af articles about marshalling in C#, but none of
them could help me to solve the following problem:

There is a C-DLL with the following header-file:

++++++++ C Header file start ++++++++++++++++++++++++++++++
#ifndef __UFISC_H
#define __UFISC_H


#ifdef UFISC_EXPORTS
#define UFIS __declspec( dllexport )
#else
#ifdef UFISC_IMPORTS
#define UFIS __declspec( dllimport )
#else
#define UFIS
#endif
#endif

//Some more code originated here
#pragma pack(push, 1)


#ifdef __cplusplus
extern "C"
{
#endif

//some more code originated here

extern unsigned char UFIS * ufisConvertToBmp24(int handle);

#ifdef __cplusplus
}
#endif


#pragma pack(pop)

#endif
++++++++ C Header file end ++++++++++++++++++++++++++++++

I need to call the function ufisConvertToBmp24 out of my C# program.

For this I wrote

[DllImport ("ufisc.dll")]
private static extern char [] ufisConvertToBmp24(int handle);

I think, this already is incorrect.

How can I call the ufisConvertToBmp24 function and retrieve the
correct value in my C# prog ?

Thanks for any help of you specialists :))

Greets

Tom
 
N

Nicholas Paldino [.NET/C# MVP]

Tom,

The declaration should look like this:

[DllImport ("ufisc.dll")]
private static extern IntPtr ufisConvertToBmp24(int handle);

The reason you do this is that it is passing back a pointer to memory,
and you need to marshal that back to a string, with a call like this:

// Call the API.
IntPtr retVal = ufisConvertToBmp24(<some value>);

// Create a string.
string val = Marshal.PtrToStringAnsi(retVal);

Here is the problem. Without knowing how the memory was allocated from
within ufisConvertToBmp24, using this method will result in a memory leak.
You should find out how to deallocate the memory, and then call that
afterwards as well (you will have to pass the pointer back to another
function).

Hope this helps.
 
T

Tom

Nicholas,

that worked just fine.

The pointer holds bytedata for a Bitmap. I've handed the IntPtr retVal
directly to System.Drawings.Bitmap-constructor and the result was
perfect :))

Thanks for your competent help !

Tom

"Nicholas Paldino [.NET/C# MVP]" <[email protected]>
wrote in
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top