hx-ffi
hx-ffi copied to clipboard
Memcpy routine of structs is incorrect with regards to memory allocation of structs by c++ compilers
typedef struct { int a; char* b; } St_n;
The c++ standard does not specify a standard way of padding/allocating structs in memory. As such the current routine, though useful needs a specification of how to specify structs:
http://stackoverflow.com/questions/5397447/struct-padding-in-c
So that the memcpy relying on ffi_type size values conforms to c++ allocation of struct members. At this time, the above struct yields a segmentation fault because the struct places the char* 8 bytes after the beginning of the struct.
Please specify this in the documentation because as you can imagine it has been quite daunting having to understand the pointer arithmetic:
const unsigned int size = t -> size;
fprintf(f,"struct size %u\n",size);
uintptr_t v = (uintptr_t) malloc(size);
uintptr_t v_start=v;
ffi_type** elem = t -> elements;
unsigned int i = 0;
uintptr_t v_char;
while(*elem != NULL) {
const ffi_type* curr = *elem;
const size_t size = curr -> size;
uintptr_t nptr = (uintptr_t) to_pointer(val_array_i(val, i), *elem);
fprintf(f,"size %d: %u\n",i,size);
if(i==1) {
fprintf(f,"b: %s\n",*(char**)nptr);
}
memcpy((void*) v, (void*) nptr, size);
if(i==1) {
fprintf(f,"v b: %s\n",*(char**)v);
v_char=v;
}
v += size;
elem++;
i++;
}
fprintf(f,"v_char bpp: %u\n",v_char);
fprintf(f,"v_char bp: %u\n",*(char**)v_char);
fprintf(f,"v_char b: %s\n",*(char**)v_char);
fprintf(f,"v_start: %u\n",v_start);
St_n st=*(St_n*)v_start;
uintptr_t stp=(uintptr_t)&st;
fprintf(f,"stp: %u\n",stp);
uintptr_t bpp=stp+4;
fprintf(f,"new bpp %u\n",bpp);
fprintf(f,"new bp %u\n",*(char**)bpp);
fprintf(f,"new b %s\n",*(char**)bpp);
fprintf(f,"st a: %d ap: %u bpp: %u b: %s\n",st.a,&st.a,&st.b,st.b);
return (void*) v_start;