DllImport and structures containing char[]

S

Stephen Richardson

I have a C++ dll which returns a structure, the structure
contains a char[21] variable, as shown below.

struct MyCStruct
{
short iNumber;
char Name[21];
};

I've declared a structure in C# as shown below

[StructureLayout[LayoutKind.Sequential)]
class MyCSharpStruct
{
short iNumber;
char[] Name;
}

when I call my dll function I pass the structure as a
LPStruct as shown below

[DllImport]
unsafe static extern bool MyDllFunction(short* iNumber,
[MarshalAs(UnmanagedType.LPStruct)]MyCSharpStruct
myStructure);

when I call this function (from an unsafe code block) I
get the error "Object reference is not set to an instance
of an object". What am I doing wrong? If I take the char
[21] element out of my C++ structure and my C# class and
call the dll everything works OK so I'm sure it the char
[] that causes the problem.
 
S

Stephen Richardson

LPStruct is one of the marshalling types (LPStruct is a
pointer to a C+ style structure). I think the problem is
due to initialising the char array but I've tried adding
this at several different points in the code and it still
gives an error. Also, why don't I have to initialise the
short?
-----Original Message-----
I don't have the ansewer but what is LPStruct
also do you have to init the char array?

[StructureLayout[LayoutKind.Sequential)]
class MyCSharpStruct
{
short iNumber;
char[21] Name; // init here?
}

I have a C++ dll which returns a structure, the structure
contains a char[21] variable, as shown below.

struct MyCStruct
{
short iNumber;
char Name[21];
};

I've declared a structure in C# as shown below

[StructureLayout[LayoutKind.Sequential)]
class MyCSharpStruct
{
short iNumber;
char[] Name;
}

when I call my dll function I pass the structure as a
LPStruct as shown below

[DllImport]
unsafe static extern bool MyDllFunction(short* iNumber,
[MarshalAs(UnmanagedType.LPStruct)]MyCSharpStruct
myStructure);

when I call this function (from an unsafe code block) I
get the error "Object reference is not set to an instance
of an object". What am I doing wrong? If I take the char
[21] element out of my C++ structure and my C# class and
call the dll everything works OK so I'm sure it the char
[] that causes the problem.


.
 

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

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top