Rust导出Python/Node.js可用的DLL库

https://blog.csdn.net/wowotuo/article/details/86251414

在处理一些计算密集型,或者系统交互较多的时候,使用编译后的程序,动态库效率会高不少,而且把相应功能封装成动态库可以便于复用,隐藏脚本语言的实现细节

一般制作DLL都是用C/C++等语言来写,不过现在又多了一种选择——Rust

创建项目:

cargo new toolib --lib
修改lib.rs文件,计算斐波那契数列:

#[no_mangle]
pub extern fn add(x1: i32,x2: i32) -> i32 {
    let r: i32 = x1 + x2;
    return r
}

pub关键字说明可以在模块外部调用该函数,extern让这个函数符合 C 调用函数的约束,另外,rust在编译时会改变函数的名称,为了让外部能够访问到这个函数,所以使用#[no_mangle]属性使编译器不修改函数的名称

在Cargo.toml 中添加一个属性:

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

编译DLL:

cargo build --release

使用 Python 调用:

import time
from ctypes import cdll

lib = cdll.LoadLibrary("target/release/orz.dll")


t1 = time.time()
result = lib.add(35,35)
t2 = time.time()

print("====== Rust ======")
print("use time: " + str(round(t2 - t1, 2)) + "s")
print("result is: " + str(result))

print(result,type(result))



posted @   Nazorine  阅读(175)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示