mozilla / cbindgen

A project for generating C bindings from Rust code
Mozilla Public License 2.0
2.43k stars 315 forks source link

Explicitly instantiate function return values that are template classes #1024

Open scovich opened 3 weeks ago

scovich commented 3 weeks ago

Following the ideas discussed in https://github.com/mozilla/cbindgen/issues/402, search the set of referenced types for templates that are function return values and emit them all as fields of a dummy struct. This silences compiler warnings (clang/gcc) and errors (MSVC) about potential ABI compatibility issues caused by returning template classes by value from extern "C" functions. We take the dummy struct approach because explicit instantiation changes semantics of C++ templates and can cause linker errors if multiple compilation units do it -- not good for a general header file.

This behavior is implemented as a new pass (similar to the existing instantiate_monomorphs pass) that is controlled by a new export config, instantiate_return_value_monomorphs. The name of the dummy struct defaults to __cbindgen_return_value_monomorphs but can be overridden by a second config.

NOTE: The PR is large because of changes to tests and expected test output. Without that, the diff is much smaller:

10 files changed, 221 insertions(+), 19 deletions(-)

Fixes https://github.com/mozilla/cbindgen/issues/402