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

孤街浪徒 提交于 2019-12-12 11:58:00

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/43660931/is-it-possible-to-use-a-c-library-from-rust-when-the-library-uses-templates-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!