Consuming C++ dlls in C# - struct definition

G

Guest

I have an unmanaged C++ dll which Iam trying to consume in C#.The code is as
below

//Unmanaged dll definition
typedef struct {
float a;
bool b;
char * c;
int d;
unsigned e;
unsigned char * f;
} sample;

//Managed C# dll definiton
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct sample
{
public float a;
public bool b;
public String c;
public int d;
public int e;
public int f;
}

[DllImport("sample.dll", EntryPoint="sendMessage")]
public static extern int sendMessage([In, Out] ref sample sampleStruct);

//Invoke method
sample sampleStruct = new sample();
sample.a = 2.00F;
sample.b = false;
sample.c = "A";
sample.d = 1;
sample.e = 3;
sample.f = 5;

response = sendMessage(ref sampleStruct);

Iam able to invoke and get the response but the invoked C++ method couldnt
read the structure passed.
Not sure whether my definitions are right. I have tried using
MarshalAs(UnmanagedType.LPStr) and SizeConstant but no luck

Any thoughts?Thanks
 
C

Crash

Raj said:
I have an unmanaged C++ dll which Iam trying to consume in C#.The code is as
below

//Unmanaged dll definition
typedef struct {
float a;
bool b;
char * c;
int d;
unsigned e;
unsigned char * f;
} sample;
....
Any thoughts?Thanks

1) You probably will need a MarshalAs for the string ptr - though I
can't find a sample right off hand...

2) Double check marshalling for the "bool". By default .NET marshals
PInvoke bools as WIN32 bools {32 bit} with values equal to WIN32 TRUE
and FALSE #defines - which is not good for C++ {8 bit} bool type...
You can marshal the bool as a char if there is no usable MarshalAs
override...
 
G

Guest

Thanks for your feedback, Crash.
I did try [MarshalAs(UnmanagedType.LPStr)] for the string but that didnt
make any difference.I also changed the bool to char but that also didnt make
any difference :-(

Iam able to retrieve all the response codes coming back in my managed code
but inovked C++ code couldnt read any values in the structure passed. Iam
sure its my definition. Not sure what it is though :-(
Thanks
Raj
 
N

Nicholas Paldino [.NET/C# MVP]

Crash,

By default, .NET marshals bool as the BOOL type (32-bits).

Also, the char type in .NET is 16 bits, not 8, so you can't use that
instead.
 

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