Hacker News new | past | comments | ask | show | jobs | submit login

Out if curiosity I've checked what c2rust.com thinks about it:

    **(*(p as *mut [*mut libc::c_int; 0])).as_mut_ptr() = 1 as libc::c_int;
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).



>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];
    }




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: