M E T A C A L L
MetaCall complete example with Function Mesh between multiple programming languages.
This example has been designed in order to illustrate how to use Rust loader through ports of other languages, especially the Python port.
This allows the users to invoke functions of rust libraries from other languages, including python, js, ruby, etc.
We can build metacall from source using following commands:
git clone --branch v0.9.22 https://github.com/metacall/core --depth 1
mkdir core/build && cd core/build
cmake \
-DNODEJS_CMAKE_DEBUG=On \
-DOPTION_BUILD_LOADERS_PY=On \
-DOPTION_BUILD_LOADERS_RS=On \
-DOPTION_BUILD_PORTS=On \
-DOPTION_BUILD_PORTS_PY=On \
-DOPTION_BUILD_DETOURS=Off \
-DOPTION_BUILD_SCRIPTS=Off \
-DOPTION_BUILD_TESTS=Off \
-DOPTION_BUILD_EXAMPLES=Off \
..
cmake --build . --target install
ldconfig /usr/local/libHere we choose to wrap melody, a language that compiles to ECMAScript regular expressions. In that way, we can create regex formula in a more readable and maintainable way, not just for rust but for many other languages.
Create a rust library, add melody as a dependency, and wrap the compile function of melody. The reason why we create a wrapper layer is that we can export the functions we need instead of all of them.
Check the src/lib.rs and you will find that it's super intuitive to wrap a function. Basically, you just write a regular rust function and mark it as pub.
After that, compile the library with cargo b.
After obtaining the Rust library, we can call it from Python using the MetaCall Python port.
The example in main.py demonstrates loading a compiled Rust package using metacall_load_from_package and invoking exported Rust functions.
The new Import API is demonstrated in load_from_file.py, where Rust source files can be imported directly using standard Python import syntax:
import metacall
from basic.rs import add, add_float_vec, add_map, new_string, string_len
assert add(1, 3) == 4No explicit call to metacall_load_from_file or metacall(...) is required when using the Import API.
This provides a more natural Python experience by allowing exported Rust functions to be imported and called directly.
Note that you should install metacall first or provide an environment variable LOADER_LIBRARY_PATH which includes metacall libraries, in order to use the python port.
# build docker image
docker build -t metacall/python-rust-example .
# run it!
docker run --rm -it metacall/python-rust-example-
load_from_file.pydemonstrates the new Import API for importing Rust source files directly from Python. -
load_from_memory.pydemonstrates loading Rust source code directly from memory. -
main.pydemonstrates loading a compiled Rust package and invoking exported functions through the MetaCall Python port.
Currently, Rust loader supports primitive types as parameters and the return value, including:
- Numeric types
- String
- Vec
- HashMap