在函数参数中使用字符串从Python调用Rust

2024-05-13 08:00:19 发布

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

我可以用整数作为输入调用testrust程序并很好地处理这些问题,即使不引用ctypes。然而,我似乎得不到一根不生锈的绳子。在

这是我的测试生锈代码:

use std::env;

#[no_mangle]
pub extern fn helloworld(names: &str ) {
  println!("{}", names);
  println!("helloworld...");
}

#[no_mangle]
pub extern fn ihelloworld(names: i32 ) {
  println!("{}", names);
  println!("ihelloworld...");
}

ihelloworld工作正常。但是,即使我使用ctypes,我也找不到一种将python中的字符串转换为Rust的方法。在

下面是调用Python的代码:

^{pr2}$

输出为:

1
ihelloworld...
Segmentation fault (core dumped)

ihellowworldRust函数工作正常,但我似乎无法使helloworld工作。在


Tags: no代码程序namesextern整数ctypeshelloworld
2条回答

我使用了the Rust FFI Omnibus,现在我的代码似乎可以正常工作。在

use std::env;
use std::ffi::{CString, CStr};
use std::os::raw::c_char;

#[no_mangle]
pub extern "C" fn helloworld(names: *const c_char) {

    unsafe {
        let c_str = CStr::from_ptr(names).to_str().unwrap();
        println!("{:?}", c_str);

    }
    println!("helloworld...");

}

从Python发送的字符串应该在Rust中表示为^{}。在

相关问题 更多 >