Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get machine-sized integer for FFI?

Tags:

int

rust

ffi

In dealing with foreign code, I have to take pointers to a C struct of the form

typedef struct {
  int two;  
  int nd;
  char typekind; 
  ...           
} PyArrayInterface;

Obviously the size of int is unknown. How do I represent this struct in rust? It's probably i32, but I might run across an ILP64 data model some day...

At this point my only idea is to create an enum to wrap the struct, check the architecture at runtime, and do the right thing. It's pretty goofy to have an if statement and a transmute each time I need to get the struct from C, but I've got nothing better at the moment...

like image 661
Jackson Loper Avatar asked Jan 21 '26 16:01

Jackson Loper


1 Answers

To handle FFI types you should use the libc crate. You can find it's documentation here.

The two types you need are libc::c_int and libc::c_char.

This chapter from the Rust book gives a neat introduction and also mentions c_int.

like image 139
Lukas Kalbertodt Avatar answered Jan 24 '26 11:01

Lukas Kalbertodt