cdylib_plugin/
lib.rs

1//! Provides workarounds for two problems encountered with ``cdylib``
2//! crates for plugin-style shared libraries, where the library refers
3//! to symbols in the host program:
4//! 1. Linking errors on some platforms due to undefined symbols
5//! 1. Difficulty finding the produced shared library for testing or installation
6
7use std::path::PathBuf;
8
9/// call from build.rs to emit build flags for building a plugin-style cdylib
10pub fn buildflags() {
11    if cfg!(target_os = "macos") {
12        println!("cargo:rustc-cdylib-link-arg=-undefined");
13        println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
14    } else if cfg!(target_os = "windows") {
15        println!("cargo:rustc-cdylib-link-arg=/FORCE");
16    }
17}
18
19/// return the absolute path of the generated cdylib, using the
20/// CARGO_PKG_NAME environment variable and the current directory.
21pub fn cdylib_path() -> PathBuf {
22    let mut path = std::env::current_dir().unwrap();
23    path.push("target");
24    if cfg!(debug_assertions) {
25        path.push("debug");
26    } else {
27        path.push("release");
28    };
29    let pkgname = std::env::var("CARGO_PKG_NAME").unwrap();
30    path.push(pkgname_to_libname(&pkgname));
31    return path;
32}
33
34fn pkgname_to_libname(name: &str) -> String {
35    let libname = name.to_string().replace("-", "_");
36    if cfg!(target_os = "windows") {
37        format!("{}.dll", libname)
38    } else if cfg!(target_os = "macos") {
39        format!("lib{}.dylib", libname)
40    } else {
41        format!("lib{}.so", libname)
42    }
43}
44
45// This crate is not itself a cdylib, so it won't produce a C shared
46// library. However, we can test that the directory exists.
47#[test]
48fn cdylib_dir_exists() {
49    let mut path = cdylib_path();
50    path.pop();
51    assert!(std::fs::metadata(path).unwrap().is_dir());
52}