2017-01-04 10 views
1

私のテストRustプログラムを整数として入力し、​​を参照しなくてもこれらを処理できます。しかし、私は錆にsegfaultingせずに文字列を取得するように見えることはできません。関数パラメータの文字列でPythonから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:ここ

は私のテスト錆コードです。しかし、​​を使っても、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錆機能がうまく動作しますが、私はhelloworld作業を取得するように見えることはできません。

+2

も参照してください[錆FFIオムニバス](http://jakegoulding.com/rust-ffi-omnibus/)及び(HTTP *多数* [錆+ Pythonの程度、既存の質問]:// stackoverflowの。 com/search?q =%5Brust%5D +%5Bpython%5D +は%3Aqです)。 – Shepmaster

+0

@Shepmasterありがとう、私は見ました、私はオムニバスがあなたのものだと推測します。私はRustのドキュメントでは見つけられないこれらの小さな点をカバーするのに良いです。 – disruptive

答えて

1

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

} 
1

Pythonから送信される文字列は、代わりにCStringとしてRustで表される必要があります。

関連する問題