Re-use a Rust C interface for multiple crates


#1

I am making a Rust version of a microservice/ messaging library called Muon (http://muoncore.io).

I intend to write a full Rust version over the next few months, but I’m starting with plugins for the other implementations (node & Java).

The idea is to write a plugin in Rust implementing some common trait (Discovery, Transport) and then expose that via a C library for FFI loading as a native shared library (so, dll etc).

I’ve done a first version crate and wrapped in FFI in java and node. worked nicely in the end.

I’m now looking to prep it all for release and extension.

What I’ve seen recommended is to have the main rust lib and the C interface hosted in different crates to ease building. This makes sense for me too, as the C interface code will never really change, whereas I’ll expect to have a bunch of plugin crates.

My question is this. Is there a way that anyone can imagine where I’d be able to share the C interface code somehow?

eg, if I had 2 plugin crates containing just Rust code, implementing a trait Discovery

muon-discovery-multicast
muon-discovery-etcd

Could there be a way to have a single repo to share the C lib interface and then use that to build 2 shared libraries, 1 for each of the above?


#2

In Rust world that would be done with generics/trait, but you can’t use generics for C functions. There’s also a problem of uniquely naming the C functions.

So I think the best you can do for generating a C interface is a massive macro that generates appropriate extern C functions with a unique name prefix/suffix.

e.g. https://github.com/KyleMayes/clang-sys/blob/master/src/link.rs


#3

Thanks! I hadn’t thought about global name clashes, but you’re right, it screws up the way I’ve been doing it.

I’ll give that a try.