I have a rust library that I want to use in my zig project. I’ve looked around for an example of how to do this, but it seems like the build system has changed a couple of times. Can someone give a simple example?
Thanks in advance!
I have a rust library that I want to use in my zig project. I’ve looked around for an example of how to do this, but it seems like the build system has changed a couple of times. Can someone give a simple example?
Thanks in advance!
Can you explain a bit more what you are hoping to accomplish here?
You may want to check out this topic: Zenoh in Zig, how to interoperate with Rust? Via C FFI?
This has a thorough discussion about how to use a Rust library that already exports a C interface.
If you are looking for an example of how to compile the rust stuff with the build system, I’m not sure of any examples. You’ll have to keep looking.
Here is another topic that seems similar: Build step cached even though file changed?
In this one, the person is calling out to Cargo to build the rust library and then linking that into Zig.
Thanks for the links! I probably won’t get a chance to look into them much until tomorrow, but it seems like the author of the second one was able to use cargo to build their rust library as part of the zig build process. I think that’s basically what I am trying to do.
A little more context. My end goal is to be able to use winit.rs in my application. My plan was to write a small C wrapper interface and use it as a dependency.
I actually just found a windowing library (sokol) that has existing zig bindings that i might try instead if this rust integration proves to be too tedious to setup.
Thanks again!
I did this at work where we have a rust library that I wanted to use in a prototype application in Zig. I ended up using the zig build system to run cargo build and using addSystemCommand to build the rust library. Then, using addInstallDirectory if needed to install the headers (but you can include these instead of installing them). And addInstallLibFile for the library artifact (or you can use linkLibrary here instead). The caveat here is that you have to parse the Cargo.toml to get the library name and target dir.
It’s kind of a PITA to get artifact paths via cargo (especially headers, see this related forum post.
Can someone give a simple example?
I did up a very simple and naive example for you here: GitHub - weskoerber/zig-link-rust-lib-example: A naive example of using Zig to build and link to a Rust library.
Note that this will break when any complexity is added – such as cross-compilation. The example is only intended to cover the basics of using addSystemCommand to build the Rust lib via Cargo and addLibraryPath/linkSystemLibrary to link the library to the Zig exe.
You may also want to look into cbindgen on the Rust side and addTranslateC on the Zig side – this will allow you to automatically export the Rust API to C and then import them into Zig.