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

在函数参数中使用字符串从Python调用Rust,python,rust,ctypes,Python,Rust,Ctypes,我可以用整数作为输入调用我的test-Rust程序,并对其进行精细处理,即使不参考ctypes。然而,我似乎无法得到一个字符串没有分段生锈 这是我的测试代码: use std::env; #[no_mangle] pub extern fn helloworld(names: &str ) { println!("{}", names); println!("helloworld..."); } #[no_mangle] pub extern fn ihelloworld(n

我可以用整数作为输入调用我的test-Rust程序,并对其进行精细处理,即使不参考
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的代码:

导入系统、类型、操作系统
从ctypes导入cdll
从ctypes导入c_char\p
从ctypes导入*
如果名称=“\uuuuu main\uuuuuuuu”:
directory=os.path.dirname(os.path.abspath(_文件__))
lib=cdll.LoadLibrary(os.path.join(目录,“target/release/libembedded.so”))
lib.ihelloworld(1)
lib.helloworld.argtypes=[c\u char\u p]
#lib.helloworld(str(“测试用户”))
#lib.helloworld(u'testuser')
helloworld(c_char_p(“测试用户”))
打印(“已完成运行!”)
输出为:

1
我的世界。。。
分段故障(堆芯转储)

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

从Python发送的字符串应该用Rust表示为a。

我使用过,现在我的代码似乎工作得很好

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...");

}

也请看,还有很多。@Shepmaster谢谢,我看了一下,我想Omnibus是你的了-它很好地涵盖了这些我在Rust文档中找不到的小问题。