Struct with array(s)

O

Olav Langeland

I am reading data to/from a file which contains C++ structures like this

struct StructCPP
{
long lDgType;
FILETIME ftDgTime;
char cName[128];
char cVersion[30];
char cSpare[98];
long lCount;
}

I am trying to access the data in the file using C# structures like this:

struct StructCSharp1 // structure without array(s)
{
public uint DgType;
public ulong DgTime;
public int Count;
};

struct StructCSharp2 // structure with arrays
{
public uint DgType;
public ulong DgTime;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)]
public byte[] Name;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=30)]
public byte[] Version;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=98)]
public byte[] Spare;
public int Count;
};

Trying to access the data in the structures:
....
unsafe
{
fixed (byte* pb = &pBuf[0]) // pointing to somewhere in the file
{
StructCSharp1 dg1 = new StructCSharp1(); // OK
StructCSharp2 dg2 = new StructCSharp2(); // OK
StructCSharp1 dg11 = *(StructCSharp1*)(pb); // OK
StructCSharp2 dg22 = *(StructCSharp2*)(pb);} // Fails
}

The last statement (dg 22 = ...) gives the compiler error:
"Cannot take the address or size of a variable of a managed type"
('...\StructCSharp2')

Any suggestions?
 
O

Olav Langeland

Mattias Sjögren said:
Olav,


Any reason you can't fill the structs member by member instead?



Mattias

Mathias,

Do you really mean like this?

unsafe
{
fixed (byte* pb = &pBuf[12])
{
int nCount = *(UInt32*)(pb +128+128+128+30+98);
}
}

If not, please advise me.
 
M

Mattias Sjögren

Olav,
Do you really mean like this?

unsafe
{
fixed (byte* pb = &pBuf[12])
{
int nCount = *(UInt32*)(pb +128+128+128+30+98);
}
}

If not, please advise me.

You don't have to use unsafe code for this. I'd do

int nCount = pBuf | pBuf[i+1] << 8 |
pBuf[i+2] << 16 | pBuf[i+3] << 32;

or use the BitConverter class.



Mattias
 

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