I am struggling with passing a struct through an FFI that accepts void and reading it back on the other end.
The library in question is libtsm, a terminal state machine. It allows you to feed input and then find out in which state a terminal would be after the input.
It declares its draw function as:
pub fn tsm_screen_draw(con: *tsm_screen, draw_cb: tsm_screen_draw_cb, data: *mut c_void) -> tsm_age_t;
where tsm_screen_draw_cb is a callback to be implemented by the library user, with the signature:
pub type tsm_screen_draw_cb = extern "C" fn(
con: *tsm_screen,
id: u32,
ch: *const uint32_t,
len: size_t,
width: uint,
posx: uint,
posy: uint,
attr: *tsm_screen_attr,
age: tsm_age_t,
data: *mut c_void
);
The important part here is the data
parameter. It allows the user to pass through a pointer to a self-implemented state, to manipulate it and use it after drawing. Given a simple struct:
struct State {
state: int
}
how would I do that properly? I am unsure how to properly cast the pointer to the struct to void and back.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…