如何让cargo test生成Rust cdylib的.so文件并在#[test]中获取?
解决cargo test生成cdylib动态库的问题
同时编译rlib和cdylib
修改Cargo.toml中的lib配置,同时指定两种 crate 类型:[[lib]] name = "mycrate" crate-type = ["cdylib", "rlib"]执行
cargo test时,Cargo会同时生成供测试代码链接的rlib库,以及你需要的cdylib动态库,.so文件直接出现在target/debug/目录下,和cargo build的输出一致。手动提取deps目录下的动态库
如果不想修改crate类型,可先编译测试(不运行),再复制并重命名动态库:cargo test --lib --no-run && cp target/debug/deps/libmycrate-*.so target/debug/libmycrate.so把这条命令存成shell脚本,方便重复调用。
在测试宏中直接定位deps目录的库
不需要复制文件的话,可在test_my_lib!宏里通过环境变量和文件匹配找到动态库:macro_rules! test_my_lib { () => { #[test] fn test_cpp_integration() { let target_dir = std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_string()); let lib_pattern = format!("{}/debug/deps/libmycrate-*.so", target_dir); let lib_path = glob::glob(&lib_pattern) .expect("Failed to glob library path") .next() .expect("No library found") .expect("Invalid library path"); // 加载库到C++应用的测试逻辑写在这里 } }; }需要在
Cargo.toml中添加glob依赖用于匹配文件:[dependencies] glob = "0.3"用自定义命令绑定构建和测试
借助cargo-make工具,在Cargo.toml中定义带前置构建步骤的测试命令:[tasks.test_with_cdylib] dependencies = ["build"] command = "cargo test"安装
cargo-make后,运行cargo make test_with_cdylib即可自动完成构建+测试流程。
内容的提问来源于stack exchange,提问作者Yuri Astrakhan
相关产品推荐
相关产品推荐

