C# fixed array in structure

D

dzar

I'm new to C# and have the following problem that I hope is simple for
you C# experts out there!

I have a need to call an unmanaged DLL (written in C) that needs the
following structure defined (C syntax):

typedef struct {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[256];
} bmBITMAPINFO;

Note how the second item is an array of 256 items and it's in that
physical block, not a reference to another block.

I'm trying to replicate this in C# so I can set up this structure and
pass it to my DLL. I don't see any obvious way to do it as arrays are
all "by reference" and this doesn't work (I need the actual data in that
structure, not a pointer to the data).

Example:

// defined in Dll.cs
public struct BmBitmapInfoStruct
{
public BITMAPINFOHEADER bmiHeader;
public RGBQUAD [] bmiColors;
}
// later... in main code...
bmi = new Dll.BmBitmapInfoStruct();
bmi.bmiColors = new Dll.RGBQUAD[256];

doesn't give the desired result as only the pointer is placed into the
structure, not the actual data.

Thanks for any insights,
Dave
 
M

Mehdi

I'm new to C# and have the following problem that I hope is simple for
you C# experts out there!

I have a need to call an unmanaged DLL (written in C) that needs the
following structure defined (C syntax):

typedef struct {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[256];
} bmBITMAPINFO;

See this article <http://www.vsj.co.uk/articles/display.asp?id=501> for an
detailled example of how to solve this kind of problem.
 
M

Mattias Sjögren

// defined in Dll.cs
public struct BmBitmapInfoStruct
{
public BITMAPINFOHEADER bmiHeader;
public RGBQUAD [] bmiColors;
}

Make it

[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]
public RGBQUAD[] bmiColors;

It only works in .NET 2.0 though.


Mattias
 
D

dzar

Mattias said:
// defined in Dll.cs
public struct BmBitmapInfoStruct
{
public BITMAPINFOHEADER bmiHeader;
public RGBQUAD [] bmiColors;
}

Make it

[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]
public RGBQUAD[] bmiColors;

It only works in .NET 2.0 though.


Mattias

Beautiful solution. Thank you.

For others who see this later, the one caveat I found was that when you
reference bmiColors, you cannot get the members of the RGBQUAD. To
overcome this I simply created a local variable of type RGBQUAD and then
assigned it to bmiColors[x].

Thanks for all the suggestions.

Dave
 

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