简体   繁体   English

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

[英]Calling Rust from Python with string in the function parameters

I can call my test Rust program with integers as input and handle these fine, even without reference to ctypes . 我可以使用整数作为输入来调用我的测试Rust程序,并且即使没有引用ctypes也可以很好地处理它们。 However I cannot seem to get a string without segfaulting in Rust. 但是,如果没有在Rust中进行段错误,我似乎无法获得字符串。

Here is my test Rust code: 这是我的测试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 works just fine. ihelloworld工作正常。 But I cannot find a way to get a string from python into Rust even if I use ctypes . 但是,即使我使用ctypes我也找不到从python获取字符串到Rust的方法。

Here is the calling Python code: 这是调用的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!")

The output is: 输出为:

1
ihelloworld...
Segmentation fault (core dumped)

The ihellowworld Rust function works just fine, but I cannot seem to get helloworld working. ihellowworld Rust函数工作正常,但我似乎无法使helloworld工作。

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

I used the Rust FFI Omnibus and now my code seems to work just fine. 我使用了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...");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM