Compiling rust .so library on Mac OS X to embed in android app

I have a rust app with JNI (for Android) and cargo toml configured for use in an Android app and can compile it into a dylib with cargo build --release but Android Studio needs a .so file. I'll eventually do similar with iOS/Swift.

Is it possible to use the cargo system to produce an .so on Mac OS X or do I need to build this on linux (on parallels, most likely)?

My cargo config seems most convenient, but I'm open to options here, whether it's converting the dylib on Mac OS X somehow, building an .so directly, building on linux (if it's just that much easier), or other thoughts.

Any reference links for building rust .so to embed in Android or iOS apps would be greatly appreciated. I've seen some that are okay-ish, they've got me this far, but running into issues since I'm on Mac OS X.

You should be able to set the crate-type key in Cargo.toml and Rust will automatically generate the *.so for you.

Here is an example from the Cargo docs:

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

Here is a link to the docs about crate types.

I would normally use crate-type =["lib", "cdylib", "staticlib"] in this situation... The cdylib will give you a *.so file for dynamically linking with a non-Rust peogram or loading at runtime, the staticlib will give you a *.a for linking statically with a non-Rust program, and lib makes sure you've got something that can be used by other rust programs (e.g. your integration tests).

Generating an Android library on a MacOS host is often called "cross-compiling" and Rust has first class support via the --target flag. The only tricky thing might be if you've got native dependencies (e.g. one of your dependencies uses a C library) because most C/C++ projects have brittle build systems.

I've found the cargo-ndk crate is pretty helpful for making your crate usable from Android.

3 Likes

Thanks! Your explanation and the cargo-ndk crate shed some light on my confusion. My target configurations were all garbled up, partly due to out-of-date examples that I "cross-confused". :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.