Previously when the code-base was in C++, I had C++ wrapper files which would link to the code base and I would run swig
(version 3 for C++11 support) to generate the interface files for the target language (Python, JavaScript, C#, etc.). Then of course get all these files and libraries compiled into a shared object and have it invoked from the required languages. Now the code base is being changed to rust. So for swig to work I have the following:
- Main rust code file compiling into an rlib.
- Rust wrapper file that calls into the main code base but uses
no_mangle
andextern
syntax forFFI
and compiles into a staticlib. - A C file that calls the rust wrapper and is a replica of it.
Now I use swig
on the C file, get the interface file for the target language, combine all the files (steps two and three) and the SWIG interface file) into a shared object and call from the target language.
So:
Is the approach fine?
I can get free functions to work. However I'm confused on how to get member functions (methods) to work. In C++ the first parameter of the member functions is the implicit
this
pointer. So I could return avoid*
handle to the class or struct to the C interface which would pass it on to others who wanted to store it (e.g. jsctypes for Firefox) and then on receiving againreinterpret_cast
it to the concrete/actual type and invoke the member function on it. How do I do this with Rust?
e.g., for
pub struct A { id: SomeType, }
impl A {
pub fn some_funct_0(&mut self) {}
pub fn some_funct_1(&self) {}
}
impl SomeTrait for A {
fn some_trait_funct(&mut self) {}
}
So how do I access these member functions on an object of A
(should be unmanaged and on the heap I guess?) from target languages (Python, C, etc.) or even simply a C interface?
self
is sugar forself: Self
,&self
forself: &Self
and&mut self
forself: &mut Self
. Sure, theself
keyword is still special in Rust, butA::some_trait_funct
andA::some_funct_0
are still functions with&mut A
as their first parameter’s type. – Chris Morganno_mangle
, creates a c-header file for that one function and runs swig on it. – oli_obk