#foreign-interface #java #jni #swig #cpp

flapigen

Tool for connecting libraries written in Rust with other languages

15 releases

0.7.0 Jun 5, 2024
0.6.0 Apr 16, 2023
0.6.0-pre9 Mar 15, 2022
0.6.0-pre7 Sep 5, 2020
0.6.0-pre13 Jul 14, 2022

#61 in FFI

Download history 604/week @ 2024-06-18 719/week @ 2024-06-25 356/week @ 2024-07-02 280/week @ 2024-07-09 364/week @ 2024-07-16 368/week @ 2024-07-23 372/week @ 2024-07-30 499/week @ 2024-08-06 343/week @ 2024-08-13 248/week @ 2024-08-20 313/week @ 2024-08-27 201/week @ 2024-09-03 231/week @ 2024-09-10 276/week @ 2024-09-17 399/week @ 2024-09-24 568/week @ 2024-10-01

1,525 downloads per month

BSD-3-Clause

800KB
22K SLoC

flapigen Build Status License Rust Documentation

Tool for connecting programs or libraries written in Rust with other languages. Foreign language api generator - flapigen. Former name rust_swig was changed to not confuse with swig. Currently implemented support for C++ and Java, but you can write support for any language of your choice. For an instruction how to integrate flapigen with your project look here.

Suppose you have the following Rust code:

struct Foo {
    data: i32
}

impl Foo {
    fn new(val: i32) -> Foo {
        Foo{data: val}
    }

    fn f(&self, a: i32, b: i32) -> i32 {
        self.data + a + b
    }

    fn set_field(&mut self, v: i32) {
        self.data = v;
    }
}

fn f2(a: i32) -> i32 {
    a * 2
}

and you want to write in Java something like this:

Foo foo = new Foo(5);
int res = foo.f(1, 2);
assert res == 8;

or in C++ something like this:

Foo foo(5);
int res = foo.f(1, 2);
assert(res == 8);

In order to implement it flapigen suggests the following functionality, in Rust project you write (in Rust language):

foreign_class!(class Foo {
    self_type Foo;
    constructor Foo::new(_: i32) -> Foo;
    fn Foo::set_field(&mut self, _: i32);
    fn Foo::f(&self, _: i32, _: i32) -> i32;
    fn f2(_: i32) -> i32;
});

and that's all, as a result flapigen generates JNI wrappers for Rust functions and Java code to call these JNI functions or generates C compatible wrappers in case of C++ and C++ code to call these C functions.

If you want the interface file (the file containing foreign_class! and so on) to be automatically generated for you, checkout rifgen.

Users Guide

📚 Read the flapigen users guide here! 📚

Dependencies

~5–13MB
~181K SLoC