Sharing a crate with crate-type = dylib

I have a rust library that does not use extern "C". (swc_common) I want to share the library among core runtime and custom plugins.

To make it a dynamic library, I used -C prefer-dynamic with

crate-type = ["lib", "dylib"]

Then I build core runtime using cargo, and verified that it links to swc_common dynamically.

Now I use allow calling functions in this dynamic library from custom plugins. I used -C prefer-dynamic and configured cargo to use rpath while building plugins.
cargo generated libswc_common.dylib and main dylib for the plugin itself.

I tried loading the built plugin dylib from core runtime, but it complained about missing dynamic library.
So I copied target/release/libswc_common.dylib to include hash string and added target/release to LD_LIBRARY_PATH.

Now it complains about missing symbols.

---- test_resolve_1 stdout ----
thread 'test_resolve_1' panicked at 'should success: failed to invoke `/Users/kdy1/projects/s/plugin-rt/plugin/node_modules/@swc/plugin-internal-test-darwin-x64/lib.dylib` as js transform plugin

Caused by:
    0: failed to load plugin
       Could not open library at:
       	dlopen(/Users/kdy1/projects/s/plugin-rt/plugin/node_modules/@swc/plugin-internal-test-darwin-x64/lib.dylib, 5): Symbol not found: __ZN10swc_common6errors7HANDLER17hdb47195cd550e3d5E
         Referenced from: /Users/kdy1/projects/s/plugin-rt/plugin/node_modules/@swc/plugin-internal-test-darwin-x64/lib.dylib
         Expected in: /Users/kdy1/projects/s/plugin-rt/plugin/runner/../../target/release/libswc_common-fed1fd40add5e453.dylib
        in /Users/kdy1/projects/s/plugin-rt/plugin/node_modules/@swc/plugin-internal-test-darwin-x64/lib.dylib

       ', plugin/runner/tests/

Can I prevent name mangling of crate-type = dylib or make them consistent?
I used same version of rustc for core runtime and plugins.

If you want a stable ABI, you have to use extern "C".


See also abi_stable crate.

It's usually better to use a cdylib that exports Rust types through a stable API. As kornel says, abi_stable can help with that.

The problem with dylib is that it's built and tested specifically for the compiler's usage so it can be a headache to work with outside of that (as you've found). This is especially true on some platforms.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.