Search code examples
intrustffi

How do I get machine-sized integer for 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...


Solution

  • 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.