mozilla / cbindgen

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

Allow access to bindings symbols names #907

Open TheElectronWill opened 7 months ago

TheElectronWill commented 7 months ago

What I'm trying to do:

  1. write a Rust library with a C-compatible interface (extern functions, etc)
  2. use cbindgen to generate a C header, to use the library from C
  3. compile a Rust program that depends on the library and links with -C link-args=-Wl,--export-dynamic-symbol=<regex of symbols to export> (or another ldd option), in order to load plugins (written in C) that use the library symbols

For step 3, I need the list of symbols in the C header. I can parse the header or fill this information by hand, but cbindgen already has the list! What is missing is a way to access it.

I can see two ways of solving this problem (both may be useful):

  1. Modify the Bindings impl: add a public API to read the items of the bindings (with methods to get the exported name of an item of any type), for instance:
    let bindings = cbindgen::Builder::new().with_crate(crate_dir).with_language(C).generate().unwrap(); // usual generation
    let symbols_names: Vec<String> = bindings.items.iter().map(|i| i.export_name()).collect(); // would be awesome if possible
  2. Add a way to export the symbols in the linker format, which looks like
    {
    symbol_1;
    symbol_2;
    };

    I will then be able to use --export-dynamic-symbol-list=<exported file> in order to export the symbols properly.

If someone guides me a little bit, I could try to implement one of the aforementioned features (or both, who knows?) :slightly_smiling_face:.