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

Calling Rust from Python with string in the function parameters

我可以使用整数作为输入来调用我的测试 Rust 程序并很好地处理这些,即使没有引用 ctypes。但是,如果没有 Rust 中的段错误,我似乎无法获得字符串。

这是我的测试 Rust 代码:

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代码如下:

import sys, ctypes, os
from ctypes import cdll
from ctypes import c_char_p
from ctypes import *


if __name__ == "__main__":
    directory = os.path.dirname(os.path.abspath(__file__))
    lib = cdll.LoadLibrary(os.path.join(directory, "target/release/libembeded.so"))

    lib.ihelloworld(1)
    lib.helloworld.argtypes = [c_char_p]
    #lib.helloworld(str("test user"))
    #lib.helloworld(u'test user')
    lib.helloworld(c_char_p("test user"))

    print("finished running!")

输出为:

1
ihelloworld...
Segmentation fault (core dumped)

ihellowworld Rust 函数工作得很好,但我似乎无法 helloworld 工作。

从 Python 发送的字符串应该在 Rust 中表示为 CString

我使用了 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...");

}