You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按此方式将字符串从Rust传递到Python是否会引发内存泄漏?

Python与Rust交互中的大整数传递问题

问题背景

我出于爱好研究Python与Rust的交互,目前卡在两种语言间的大整数传递上:

  • 从Python传大整数到Rust很简单:转成32位整数数组即可,Rust处理起来毫无障碍。
  • 但反向传递(Rust到Python)存在麻烦,Rust并不擅长向外部接口传递数组。

我想到一个解决方案:把大整数转换为字符串后传给Python,再由Python转回整数。这个方法看似可行,但参考相关回答后,担心会引发内存泄漏。另外,尝试在Python接收字符串后立即调用推荐的free函数时,触发了core dumped错误。

原始Rust代码

const MAX_DIGITS: usize = 100;

unsafe fn import_bigint(digit_list: PortableDigitList) -> BigInt {
    let digits = Vec::from(*digit_list.array);
    let result = BigInt::new(Sign::Plus, digits);

    return result;
}

fn export_bigint(n: BigInt) -> *mut c_char {
    let result_str = n.to_str_radix(STANDARD_RADIX);
    let result = CString::new(result_str).unwrap().into_raw();

    return result;
}

#[repr(C)]
pub struct PortableDigitList {
    array: *const [u32; MAX_DIGITS]
}

#[no_mangle]
pub unsafe extern fn echo_big_integer(
    digit_list: PortableDigitList
) -> *mut c_char {
    let big_integer = import_bigint(digit_list);

    println!("Received big integer: {:?}. Sending it back...", big_integer);

    return export_bigint(big_integer);
}

最小可复现示例(MWE)

lib.rs代码

use std::ffi::CString;

use libc::c_char;

#[no_mangle]
pub unsafe extern fn return_string() -> *mut c_char {
    let result_string = "4294967296";

    println!("Returning string to Python: {}", result_string);

    let result = CString::new(result_string).unwrap().into_raw();

    return result;
}

#[no_mangle]
pub unsafe extern fn free_string(pointer: *mut c_char) {
    let _ = CString::from_raw(pointer);
}

Cargo.toml配置

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

[lib]
name = "return_string"
crate-type = ["dylib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libc = "0.2.152"

Python调用代码

from ctypes import CDLL, c_char_p, cast

lib = CDLL("return_string/target/release/libreturn_string.so")

rust_func = lib.return_string
rust_func.restype = c_char_p
result_pointer = rust_func()
result = cast(result_pointer, c_char_p).value.decode()
print("Rust returned string: "+result)

free_func = lib.free_string
free_func.argtypes = [c_char_p]
free_func(result_pointer)

运行输出

Returning string to Python: 4294967296
Rust returned string: 4294967296
munmap_chunk(): invalid pointer
Aborted (core dumped)

内容的提问来源于stack exchange,提问作者Tom Hosker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:13:10