Search code examples
cserializationmpivoid-pointerspointer-arithmetic

Pointer arithmetic on raw data


So I have to process some struct data which I've had to compress in a weird way for MPI_Send/Recv.

There's no way to comfortably cast it to a pointer to a known type on which I want to operate and then index along (since I've squeezed the struct into contiguous data, can't assume anything about alignment), so I have to go through it with pointer arithmetic. Problem is, to keep consistent with MPI, this data is given as void*, and pointer arithmetic on void* is illegal.

My question is mostly stylistic: is there a better way to do this than to cast to char* and then do my pointer arithmetic? What would be the efficiency considerations in taking a void*, casting to char*, doing my stuff to it, then casting back to void*? I can't imagine that pointer casts would be terribly expensive.

G'day and thankee much.


Solution

  • Pointer casts are completely free. Do it.

    A pointer having a type is an entirely language level notion. When you get down to the hardware level a pointer is just an integer that happens to be used as a memory address.

    You do have to be careful about strict aliasing, when casting pointers about, but char * is defined to be safe, I think.

    [OK, there are some cases, on some architectures, where pointers have special handling beyond "just being integers", but you can probably ignore those. There are also some ABIs in which different pointer types are different (FDPIC, for instance), but again, somebody else's problem.]