Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How I cast from a unsigned char __gc[] to a struct?

Status
Not open for further replies.

perro2

Programmer
Joined
Dec 20, 2002
Messages
1
Location
EC
I am programming en Visual C++ .NET. I have an unsigned char array, and I need to cast it to a struct that I created. The struct I defined is the following:

struct datagramaIP {
unsigned int longCabecera:4;
unsigned int version:4;
unsigned int tipoServicio:8;
unsigned int longTotal:16;
unsigned int idFragmento:16;
unsigned int despFragmento:13;
unsigned int fragmentosAdicionales:1;
unsigned int noFragmentar:1;
unsigned int reservado:1;
unsigned int TTL:8;
unsigned int protocolo:8;
unsigned int checksumCabecera:16;
unsigned char dirIPFuente[4];
unsigned char dirIPDest[4];
unsigned char *opciones;
unsigned char *datos;
};

And I defined a variable like this:

unsigned char datagrama __gc[] = new unsigned char __gc[1500];

I need to store the contents in datagrama in a variable of the struct I defined above. How I can do it?

I tried do that with static_cast in the following manner:

struct datagramaIP *ip = static_cast<struct datagramaIP *>(datagrama);

but it gives me an error in compilation time. The error is:

error C2440: 'static_cast' : no se puede realizar la conversión de 'unsigned char __gc[]' a 'datagramaIP *'
 
Why not
struct datagramaIP *ip = (struct datagramaIP *)datagrama;
?
static_cast, I think, is for casting of derived classes only.

Also you must care, that your pointer of char array was alligned on int border (the address must be divisible by 4). Better approach would be allocation of both objects - char array and structure - and copying of the data using memcpy().
 
I think you will have padding issues with the declaration of the struct

struct datagramaIP {
unsigned int longCabecera:4;
unsigned int version:4;
unsigned int tipoServicio:8;
unsigned int longTotal:16;
unsigned int idFragmento:16;
unsigned int despFragmento:13;
unsigned int fragmentosAdicionales:1;
unsigned int noFragmentar:1;
unsigned int reservado:1;
unsigned int TTL:8;
unsigned int protocolo:8;
unsigned int checksumCabecera:16;
unsigned char dirIPFuente[4];
unsigned char dirIPDest[4];
unsigned char *opciones;
unsigned char *datos;
};


the :1's will cause obscure padding.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top