Re:Using Zig's translate-C to understand weird C code
by pornel on Wednesday November 03, 2021 @08:02AM
(#29093472)
Out if curiosity I've checked what c2rust.com thinks about it:
which is still needlessly complicated, and not even quite accurate due to giving the array a 0 size (the as_mut_ptr() converts the array back to a C pointer).
[ Parent
| on HN ]
Re:Using Zig's translate-C to understand weird C code
by Arnavion on Wednesday November 03, 2021 @04:30PM
(#29099868)
>and not even quite accurate due to giving the array a 0 size (the as_mut_ptr() converts the array back to a C pointer).
It doesn't seem inaccurate to me, more like the best choice at hand. If the C array has a known length, the Rust code has it too. Only if the C code has an array of unknown length does the Rust code use a 0-length array. Furthermore, if the C code indexes the array of unknown length, the Rust code uses .as_mut_ptr().offset(...) instead of directly indexing the array. So the fact that it represents C arrays of unknown length with Rust arrays of 0 length does not cause any problem, because the generated code is consistent.
char foo(void* p) {
char (*arr)[] = (char (*)[])p;
return (*arr)[1];
}
char bar(void* p) {
char (*arr)[3] = (char (*)[3])p;
return (*arr)[1];
}
... translates to: pub unsafe extern "C" fn foo(mut p: *mut libc::c_void) -> libc::c_char {
let mut arr: *mut [libc::c_char; 0] = p as *mut [libc::c_char; 0];
return *(*arr).as_mut_ptr().offset(1 as libc::c_int as isize);
}
pub unsafe extern "C" fn bar(mut p: *mut libc::c_void) -> libc::c_char {
let mut arr: *mut [libc::c_char; 3] = p as *mut [libc::c_char; 3];
return (*arr)[1 as libc::c_int as usize];
}