5
votes

Is it possible to use a C++ library from Rust when the library (e.g. Boost) uses templates (generics)?

1
Last I heard, C++ does not have a stable ABI, so you cannot call any C++ library from another language. You need to create a C shim, like projects such as LLVM do.Shepmaster
@Shepmaster “C++ does not have a stable ABI” doesn’t mean that individual compilers don’t provide (maybe even stable) ABIs that support templates. It might be entirely possible to call clang-compiled C++ code from Rust, for instance. For now, rustc uses LLVM as the backend so this should in principle be feasible.Konrad Rudolph
You have a totally different problem: even if you get the ABI problems resolved, rustc couldn't monomorphize a C++ function that isn't already monomorphized by the C++ compiler without invoking the C++ compiler.oli_obk
templates works by instancing peices of C++ code with different c++ type/values. You'll literally need a C++ compiler inside your rust compiler and something in between that understands both language so it can translate the code on the fly. Some construct in C++ don't exist in rust (eg, variadic templates) so there is little change of this happening.Guillaume Racicot

1 Answers

8
votes

Yes, but it may not be practical.


The D programming language is one of the very few providing some degree of C++ interoperability; you can read more about it on dlang.

Note the limitation for the template section:

Note that all instantiations used in D code must be provided by linking to C++ object code or shared libraries containing the instantiations.

which essentially means that you must use C++ code to cause the instantiation of the templates with the right types, and then the D compiler will link against those instantiations.


You could do the same for Rust. Without compiler support, this means mangling the names manually. In the FFI section, you will find the link attribute:

#[link(name = "snappy")]
extern {
    fn snappy_max_compressed_length(source_length: size_t) -> size_t;
}

which tells the compiler which linked library will provide the symbol, you will also support for various calling conventions and the no_mangle attribute.

You may need to apply #[allow(non_snake_case)] as appropriate.


Servo uses bindgen to generate Rust bindings for C and C++ code; I am unclear on the level of C++ support, and somewhat doubtful that it can handle templates.