Having asked a question recently about casting a byte buffer to a struct and receiving an excellent response from Mattias Sjorgen (sorry about that o ;) which resulted in the following code
struct rec01
ushort rt
..
byte[] buffer = new byte[512]
rec01 rec
// fill buffer with dat
unsafe
fixed (byte *p = buffer) {
rec = *((rec01*)p)
Now this works, but I am now stuck on something else... The structures I want to replicate in c# from c++ are of the type
struct rec01
__int16 rt
char id[10]
char name[32]
..
I've tried using the following for the id field
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=10)
string id;
and
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)
byte[] id;
but both yield the same compile error on the above buffer/struct cast !
Does anybody have any ideas or is this type of thing not possible in c#
Thanks in advance
>from Mattias Sjorgen (sorry about that o ;)
Close enough :)
>Does anybody have any ideas or is this type of thing not possible in c# ?
No, unsafe code only works on value types without any reference type
members, which unfortunately excludes arrays and strings.
So the other option is probably to work with the Marshal class
instead. Here are some egeneric routines for copying a struct to/from
a byte array
http://groups.google.com/groups?selm=%237tARJk5BHA.1656%40tkmsftngp05
FWIW, C# v2 will have a solution to this, letting you write
unsafe struct rec01 {
public short rt;
public fixed byte id[10];
public fixed byte name[32];
...
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.