Hi, I'm now implementing generators of Rust, and I faced a problem.
In order for the wrapper to 'understand' the struct passed from C API, it
is required to incorporate the definition of the struct in C into Rust
code.
I have two approaches.
1. Create raw struct(#[repr(C)]), which has the equivalent memory mapping
to C struct and access through this struct in Rust
2. Use bindgen to create ffi struct from guestfs.h
Each of them has advantages and disadvantages.
# 1st approach
This is highly dependent on the implementation of API because it is subject
to the memory mapping of API struct. When the way struct is structured
changes in API, you have to modify Rust bindings. In order to avoid this
situation, you can define the same struct in C and Rust and then access the
API struct in C and then Rust accesses the data through this struct. This
means that
```
API:
struct guestfs_A:
- field: x FString
C:
struct RawA {
char* x
};
struct RawA to_RawA(struct guestfs_A* src) {
struct RawA x = {src->x};
return x;
}
Rust:
#repr(C)
use std::ffi::CStr;
use std::str;
#[repr(C)]
struct RawA {
x: *const i8
}
enum guestfs_A {} // opaque struct
extern {
fn to_RawA( src: *const guestfs_A ) -> RawA;
}
struct A {
x: String
}
impl A {
fn new(src: *const guestfs_A) -> A {
let dst = unsafe {to_RawA(src)};
let c_str = unsafe { CStr::from_ptr(dst.x) };
let s = c_str.to_str().unwrap().to_string();
A{ x: s }
}
}
```
This is a little verbose and inefficient.
# 2nd approach
The above is easily done by 'bindgen', which automatically generates rust
ffi bindings to C library. By using this, API struct is automatically
generated. However, it requires a new dependency: libclang.
# Question
Which of these approaches is more preferable?
Regards,
Hiroyuki Katsura