Mixing Xojo and Rust libs

Rust is slowly overtaking C++. Microsoft, Google, and many others are switching to it step by step, even Linus Torvalds is switching part of the Linux code to Rust.

So, as today we had a question about creating a DLL in C and use it in Xojo, I though how hard (or easy) it would be the same in Rust.

So here are the steps:


Create the following tree of files:

xojo_rust
│
│   Cargo.toml
│
└───src
        lib.rs

xojo_rust and src are folders
Cargo.toml is the project specification
lib.rs is our DLL code in Rust


Cargo.toml contents:

[package]
name = "xojorust"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]

lib.rs contents (yep, 4 lines):

#[no_mangle]   // export symbol as is
pub fn double_value(value: i32) -> i32 { // return the double value as Int32
    2 * value
}

It’s done.

Compile it going to the root folder xojo_rust and …

cargo build


You will end with something like this tree:

xojo_rust
│   .gitignore
│   Cargo.lock
│   Cargo.toml
│
├───src
│       lib.rs
│
└───target
    │   .rustc_info.json
    │   CACHEDIR.TAG
    │
    └───debug
        │   .cargo-lock
        │   xojorust.d
        │   xojorust.dll
        │   xojorust.dll.exp
        │   xojorust.dll.lib
        │   xojorust.pdb
        │
        ├───.fingerprint
        │   └───xojorust-6beb2fdf8a7024f9
        │           dep-lib-xojorust
        │           invoked.timestamp
        │           lib-xojorust
        │           lib-xojorust.json
        │
        ├───build
        ├───deps
        │       xojorust.d
        │       xojorust.dll
        │       xojorust.dll.exp
        │       xojorust.dll.lib
        │       xojorust.pdb
        │
        ├───examples
        └───incremental
            └───xojorust-3bhhw63dtmlw9
                │   s-gqcmv35bwe-1yvw50a.lock
                │
                └───s-gqcmv35bwe-1yvw50a-cn6ma2xqr28n52p6d9q4kyr9w
                        4zl3vjlcauf06loi.o
                        dep-graph.bin
                        query-cache.bin
                        work-products.bin

Notice the lib at .\target\debug\xojorust.dll


Let’s try it!

image

It works!

Have fun. :wink:

14 Likes

You can later build the release, optimized. Add --release

It goes into the target/release folder

3 Likes