Call foreign member functions using Panama
Gavin Ray
ray.gavin97 at gmail.com
Sun Nov 27 17:09:18 UTC 2022
It's possible to use Panama to interact with C++ and Rust etc
It requires an understanding of implementation details of the
underlying platform, and puts you at risk of breakage if the
underlying ABI changes.
For example, here is how you can create an instance of a C++ class
with member functions from C:
Given some class definition like:
class BaseThing {
public:
virtual void someVirtual() = 0;
};
We can dump the layout of this with Clang/GCC like this:
- https://gist.github.com/GavinRay97/700ff1631d7e5ac460efd0780759c908
And then based on knowing the vtable layout, we can represent it as C
structs filled with function pointers.
Here's an example showing a C++ class with member functions,
implemented as both a C++ derived class & C raw vtable struct:
- https://godbolt.org/z/6YPPqj9KG
There are even tools that can take C++/Rust headers and dump the
vtable layouts like these automatically as C headers, which you can
then use via jextract:
- https://blog.trailofbits.com/2022/01/19/c-your-data-structures-with-rellic-headergen
- https://github.com/hidva/clayout
On Sat, Nov 26, 2022 at 9:47 PM Samuel Audet <samuel.audet at gmail.com> wrote:
>
> Anything outside platform ABIs for C is out of scope for Panama. Since
> Clang, which is essentially becoming the reference C++ implementation,
> and Rust are based on LLVM, something like Sulong is probably the way to
> go for that:
>
> https://github.com/oracle/graal/tree/master/sulong
> https://github.com/oracle/graal/blob/master/sulong/docs/contributor/INTEROP.md
>
> Samuel
>
>
> On 11/26/22 15:57, Red IO wrote:
> > I was building a small framework to connect rust and java (jdk 11) for a
> > project. I build a java class with 1 field a long. Then I added non
> > static native functions to the class representing the member functions
> > of the corresponding rust struct. I mangled myself through the jni
> > nightmare and stored a reference to the rust struct in the long. This
> > construct simulates first class foreign member function support pretty
> > well. After building this I thought about Panama. As far as I know
> > Panama currently only supports C (no concept of member functions).
> > Wouldn't it be a good idea to support languages like c++, rust and their
> > member functions? I mean with Panama we can already create foreign
> > structs. Would it be so far fetched to integrate constructors and member
> > functions into Panama and jextract?
> >
> > Great regards
> > RedIODev
>
More information about the panama-dev
mailing list