温馨提示×

如何在Linux上集成Rust与其他编程语言

小樊
39
2026-01-06 19:44:05
栏目: 编程语言

在Linux上集成Rust与其他编程语言可以通过多种方式实现,以下是一些常见的方法:

1. 使用FFI(Foreign Function Interface)

FFI允许你在Rust中调用其他语言编写的函数,反之亦然。以下是使用FFI集成Rust和C语言的示例:

Rust端

首先,创建一个Rust库项目:

cargo new --lib my_rust_lib
cd my_rust_lib

Cargo.toml中添加以下内容:

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

[dependencies]
libc = "0.2"

src/lib.rs中编写Rust代码并导出函数:

#[no_mangle]
pub extern "C" fn rust_function() {
    println!("Hello from Rust!");
}

编译Rust库:

cargo build --release

C端

创建一个C文件(例如main.c)并调用Rust函数:

#include <stdio.h>
#include <stdlib.h>

// 声明Rust函数
extern void rust_function();

int main() {
    printf("Calling Rust function...\n");
    rust_function();
    return 0;
}

编译C程序并链接Rust库:

gcc -o my_c_program main.c -Ltarget/release -lmy_rust_lib -lpthread -ldl

运行C程序:

./my_c_program

2. 使用Python的ctypes

如果你想在Python中使用Rust编写的库,可以使用ctypes库。

Rust端

按照上面的步骤创建Rust库,并确保导出函数:

#[no_mangle]
pub extern "C" fn rust_function() {
    println!("Hello from Rust!");
}

编译Rust库:

cargo build --release

Python端

安装ctypes库(通常Python自带),然后编写Python代码调用Rust函数:

import ctypes

# 加载Rust库
rust_lib = ctypes.CDLL('./target/release/libmy_rust_lib.so')

# 调用Rust函数
rust_lib.rust_function()

运行Python脚本:

python my_python_script.py

3. 使用Node.js的ffi-napi

如果你想在Node.js中使用Rust编写的库,可以使用ffi-napi库。

Rust端

按照上面的步骤创建Rust库,并确保导出函数:

#[no_mangle]
pub extern "C" fn rust_function() {
    println!("Hello from Rust!");
}

编译Rust库:

cargo build --release

Node.js端

安装ffi-napi库:

npm install ffi-napi

编写Node.js代码调用Rust函数:

const ffi = require('ffi-napi');
const ref = require('ref-napi');

// 定义Rust库的路径和函数签名
const myRustLib = ffi.Library('./target/release/libmy_rust_lib.so', {
  'rust_function': ['void', []]
});

// 调用Rust函数
myRustLib.rust_function();

运行Node.js脚本:

node my_node_script.js

4. 使用WebAssembly(Wasm)

如果你想在浏览器中使用Rust编写的代码,可以将其编译为WebAssembly。

Rust端

安装wasm-pack工具:

cargo install wasm-pack

创建一个新的Rust项目并配置为Wasm:

cargo new --lib my_wasm_lib
cd my_wasm_lib

Cargo.toml中添加以下内容:

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

[dependencies]
wasm-bindgen = "0.2"

src/lib.rs中编写Rust代码并导出函数:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn rust_function() {
    web_sys::console::log_1(&"Hello from Rust!".into());
}

编译为Wasm:

wasm-pack build --target web

JavaScript端

在你的HTML文件中引入生成的Wasm文件并调用Rust函数:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Rust + WebAssembly</title>
</head>
<body>
    <script type="module">
        import init, { rust_function } from './pkg/my_wasm_lib.js';

        async function run() {
            await init();
            rust_function();
        }

        run();
    </script>
</body>
</html>

通过这些方法,你可以在Linux上集成Rust与其他编程语言,实现跨语言的互操作。

0