Recasting byte array to struct without pointers

Technical questions regarding the XTC tools and programming with XMOS.
kster59
XCore Addict
Posts: 162
Joined: Thu Dec 31, 2009 8:51 am

Recasting byte array to struct without pointers

Post by kster59 »

Often times I receive data into a char array and want to put it into a struct.

In C I can do:

typedef struct
{
int id;
char[50] text;
} MESSAGE;

// Receive a message
char buffer[100];
recv(socket, buffer, 100);
MESSAGE* msg = (MESSAGE*)buffer;
printf("id=%d\n", msg->id);
printf("text=%s\n", msg->text);

How do I do this in Xc without pointers?

I can create a new structure then pass this to a C/C++ header and do a memcpy but this seems like a waste compared to recasting a pointer like I can in C/C++.


richard
Respected Member
Posts: 318
Joined: Tue Dec 15, 2009 12:46 am

Post by richard »

You can use a reinterpret cast to interpret an object as another type. For example to reinterpret a struct to an array of bytes you can use the following:

Code: Select all

void f(char c[]);

void g() {
  struct foo s;
  f((s, char []));
}
You could also reinterpret the other way around (from a char array to the struct), but if you reinterpret to a type with a greater alignment requirement then you might get a runtime trap due to a misaligned load or store.
mculibrk
Active Member
Posts: 38
Joined: Tue Jul 13, 2010 2:57 pm

Post by mculibrk »

Is there any #pragma related to the reinterpretation?
From the decs the reinterpretation is taking a lot of "care" about object of different sizes etc. I did not check the code generated but anyway is there a way to "force" the compiler/code not to check anything around reinterpretation (type casts)?

The other question is about "functions in function" like this

Code: Select all

int masterFunc(int A, int B) {
  int localVarA, localX;

  int subFunc(int X) {
    return X + localVarA;
  }

  localX = subFunc(A);
}
I found no mention of such constructs in the XC "guide" but the compiler won't swallow anything similar I thrown at it.

regards,
mculibrk