0

I have this code in my header file:

typedef struct _game* Game;

Right now to FFI from Rust I'm doing:

extern "C" {
    pub type Game = usize;
}

Is there a safer way to do this than to treat it like a pointer-sized numeric type? Would this work:

pub struct Game(usize);
Shien
  • 495
  • 5
  • 13
  • Seems suspiciously similar to http://stackoverflow.com/questions/22116547/in-rust-how-can-i-define-or-import-a-c-struct-from-a-third-party-library however the answer to this question (by the same author) is more up-to-date vis a vis the guidelines – Matthieu M. Jun 14 '16 at 11:53

1 Answers1

3

You usually model abstract C types in Rust using a pointer to an empty enum:

pub enum _game {}
pub type Game = *mut _game;

This approach explicitly highlights the fact that you cannot create values of _game yourself - you can only get a pointer to it from somewhere.

That said, if you're writing a more high-level wrapper for your library, you should wrap this Game into a more high-level Game, like this:

extern crate your_library_sys;

pub struct Game(your_library_sys::Game);

Here your_library_sys is a "sys" crate which contains low-level FFI bindings to the library. This is a convention which is described in Cargo docs.

Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296