Skip to content

Commit e55954f

Browse files
committed
Use macro for defining struct ffi
1 parent 7d0191a commit e55954f

File tree

4 files changed

+33
-14
lines changed

4 files changed

+33
-14
lines changed

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ name = "specs-ffi"
33
version = "0.1.0"
44
authors = ["torkleyy <torkleyy@gmail.com>"]
55

6+
[lib]
7+
crate-type = ["dylib"]
8+
69
[dependencies]
710
shred = "0.5"
811
specs = "0.10"

src/lib.rs

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,8 @@
1-
#![no_mangle]
2-
31
extern crate shred;
42
extern crate specs;
53

6-
#[repr(C)]
7-
pub struct SpecsWorld(pub specs::World);
8-
9-
pub fn create_world() -> *mut SpecsWorld {
10-
let world = SpecsWorld(specs::World::new());
11-
let world = Box::new(world);
12-
13-
Box::into_raw(world)
14-
}
4+
pub use world::*;
155

16-
pub fn free_world(w: *mut SpecsWorld) {
17-
unsafe { Box::from_raw(w); }
18-
}
6+
#[macro_use]
7+
mod macros;
8+
mod world;

src/macros.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
#[macro_export]
3+
macro_rules! c_struct {
4+
($name:ident, $wrap:ty, $create:ident => $( $params:ident ),* => $new:expr => $free:ident) => {
5+
#[repr(C)]
6+
pub struct $name(pub $wrap);
7+
8+
#[no_mangle]
9+
pub fn $create($($params ,)*) -> *mut $name {
10+
let val = $name($new);
11+
let val = Box::new(val);
12+
13+
Box::into_raw(val)
14+
}
15+
16+
#[no_mangle]
17+
pub fn $free(val: *mut $name) {
18+
unsafe { Box::from_raw(val); }
19+
}
20+
};
21+
}

src/world.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#![no_mangle]
2+
3+
use specs;
4+
5+
c_struct!(SpecsWorld, specs::World, create_world => => specs::World::new() => free_world);

0 commit comments

Comments
 (0)