DllImport and structures containing char[]

  • Thread starter Thread starter Stephen Richardson
  • Start date Start date
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.
 
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.


.
 
Back
Top