casting a bit array to a structure

J

Joe Thompson

Using VS.Net 2003 - a managed VC++ WinForms app:

If I have an unmanged structure like

typedef struct
{
unsigned char Field1;
unsigned char Field2;
unsigned int Field3: 6;
unsigned int Field4: 2;
} MYSTRUCT;

and a managed byte array btArr that is 3 bytes long, what is the syntax to
convert the byte array to a MYSTRUCT?

MYSTRUCT *ms = (MYSTRUCT*)btArr;

does not work (or compile for that matter).

Thank you,
Joe
 
L

lallous

I don't know about btAttr's definition, however and in worst cases can't you
write a function that does the member-wise copying ?

MYSTRUCT s1;
s1.fld1 = btAttr.fld1;
s1.fld2 = btAttr.fld2;

etc...
 
J

Joe Thompson

Hi - it's a byte array declared like this:

Byte btArray[] = new __gc Byte[3];

I really have a much larger structure and array that I am reading from the
serial port and would prefer to move it to my structure quickly. Also, some
of my fields in the structure are larger than one byte and some smaller
(bit-fields)

Joe
 
R

Ronald Laeremans [MSFT]

You need to __pin the managed array. Look for that keyword in the docs. Let
me know if the help there isn't enough, and I'll try to post an example.

Ronald Laeremans
Visal C++ team
 
G

Guest

Hi Ronald

After a few attempts, I think I got it - does this look right

int avail = 1024

Byte btArr[] = new Byte[avail]
ComPort->Read(btArr, 0, avail); // this wants a Byte arra
Byte __pin *p = &btArr[1]; // entire array is now pinne
MYSTRUCT *ms = (MYSTRUCT*)p;

Thank you
Joe
 
R

Ronald Laeremans [MSFT]

Yes, that looks fine. Make sure you don't keep ms alive (e.g. by passing it
back to the caller of this code block) after *p goes out of scope, otherwise
it will no longer be pinned and could move.

Ronald
 
J

Joe Thompson

I think that sould have been

&btArr[0];
not
&btArr[1];

Thanks for the help,
Joe

Ronald Laeremans said:
Yes, that looks fine. Make sure you don't keep ms alive (e.g. by passing it
back to the caller of this code block) after *p goes out of scope, otherwise
it will no longer be pinned and could move.

Ronald

Joe Thompson said:
Hi Ronald,

After a few attempts, I think I got it - does this look right?

int avail = 1024;

Byte btArr[] = new Byte[avail];
ComPort->Read(btArr, 0, avail); // this wants a Byte array
Byte __pin *p = &btArr[1]; // entire array is now pinned
MYSTRUCT *ms = (MYSTRUCT*)p;

Thank you,
Joe
 

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