Skip to content

Instantly share code, notes, and snippets.

@CoolOppo
Last active September 15, 2024 10:55
Show Gist options
  • Save CoolOppo/67b452c125bb0db3212a9fbc44c84245 to your computer and use it in GitHub Desktop.
Save CoolOppo/67b452c125bb0db3212a9fbc44c84245 to your computer and use it in GitHub Desktop.
How to compile to a DLL in rust while using it as a normal rust library

How to use the same lib you are exporting as a DLL from within Rust

Note: if you don't want to export as a DLL and just want to use a library from the same crate as your binary, just remove everything below edition = "2018" and the no_mangle and externs from the lib.rs example here.

I couldn't find any good info on this for some reason, but here is what you need to do in order to accomplish this with minimal extra configuration. The bin (main.rs) is also what will be compiled/run when you type cargo run, which means you don't lose the convenience of having a standalone bin project.

Use cargo build --lib to build the .dll/.so itself.

Directory tree:

│   Cargo.toml
│
└───src/
        lib.rs
        main.rs

SEO:

  • Use rust.rs and lib.rs in same project
  • Use lib.rs as DLL
  • Export normal rust lib as DLL
  • Use exported rust-lang library from within rust-lang
  • Use rust DLL without unsafe (note that the final executable won't actually use the library as a DLL, but I am trying to catch people who are searching for solutions to the same problem I was having)
[package]
name = "test"
version = "0.1.0"
authors = ["YOU <[email protected]>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
#[no_mangle]
pub extern fn lib_test() {
println!("Hello from the library!");
}
mod lib;
use crate::lib::*;
fn main() {
lib_test();
}
@Sierra021
Copy link

thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment