Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / Interop / August 2003

Tip: Looking for answers? Try searching our database.

structure with char[]

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Stephen Richardson - 20 Aug 2003 23:31 GMT
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.

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.