如何在Rust和Python之间传递指针?

2024-06-25 05:39:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Rust编写一个可以从Python代码调用的库。我希望能够将一个void指针传递回Python,这样就可以在调用Rust之间保持状态。但是,当我再次尝试访问指针时,在Rust中出现了一个segfault。在

完整的代码示例和崩溃报告:https://gist.github.com/robyoung/3644f13a05c95cb1b947

代码

#![feature(libc)]
#![feature(alloc)]
extern crate libc;
use std::boxed;

pub struct Point {
    x: i64,
    y: i32,
}

#[no_mangle]
pub extern "C" fn start_state() -> *mut Point {
    let point = Box::new(Point{x: 0, y: 10});
    let raw = unsafe { boxed::into_raw(point) };
    println!("{:?}", raw);
    raw
}

#[no_mangle]
pub extern "C" fn continue_state(point: *mut Point) -> i32 {
    println!("{:?}", point);
    let p = unsafe { Box::from_raw(point) };
    println!("{} {}", p.x, p.y);
    0
}
^{pr2}$

输出

0xdc24000
10dc24000
0xdc24000
[1]    64006 segmentation fault  python src/main.py

我做错什么了?在


Tags: no代码rawexternrustfeaturepointlibc
1条回答
网友
1楼 · 发布于 2024-06-25 05:39:51

eryksun nailed it

On the Python side, you're missing lib.continue_state.argtypes = (ctypes.c_void_p,). Without defining the parameter as a pointer, ctypes uses the default conversion for a Python integer, which truncates the value to 32-bit, e.g. 0x0dc24000. If you're lucky accessing that address triggers a segfault immediately.

我的输出(加上我自己的填充)是:

0x103424000
  103424000
0x  3424000

因此,指针的Debug格式化程序应该很好。不知道为什么你的输出不同。在

添加后

^{pr2}$

程序运行得很好。在

相关问题 更多 >