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)
short iNumber = 1;
MyCSharpStruct myStructure = new MyCSharpStruct();
MyDllFunction(&iNumber,myStructure);
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. Is it because char in
C# is 16bit? I added CharSet = CharSet.Ansi to the
DllImport but it doesn't make any difference. Is it
because I have to initialise the C# char array? Where do
I have to do this?
David Stucki [MS] - 26 Aug 2003 19:00 GMT
Have you tried using MarshalAs(UnmanagedType.ByValTStr)]?
[StructureLayout[LayoutKind.Sequential, CharSet=CharSet=Ansi)]
class MyCSharpStruct
{
short iNumber;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=21)]
string Name;
}
[DllImport]
static extern bool MyDllFunction(ref short iNumber, ref MyCSharpStruct
myStructure);
Hope this helps,
David Stucki
Microsoft Developer Support
This posting is provided "AS IS" with no warranties, and confers no rights.