正如标题所述,当我尝试在Python中调用以下Rust代码时,我收到了访问冲突。
这是Rust代码:
#![crate_type = "dylib"]
extern crate libc;
use libc::c_char;
use std::ffi::CStr;
use std::str;
#[repr(C)]
pub struct AdditionalDetail {
swis: String,
sbl: String,
school_code: String,
land_assessed_value: u32,
deed_book: String,
deed_page: String,
}
#[no_mangle]
pub extern fn parse_details(l: *const c_char) -> AdditionalDetail{
let _line = unsafe {
assert!(!l.is_null());
CStr::from_ptr(l)
};
let line = str::from_utf8(_line.to_bytes()).unwrap();
let _swis = line[52..58].to_owned();
let _sbl = line[58..78].to_owned();
let _school_code = line[371..377].to_owned();
let _land_assessed_value = line[824..836].parse::<u32>().ok().expect("Couldn't convert to an int");
let _deed_book = line[814..819].to_owned();
let _deed_page = line[819..824].to_owned();
AdditionalDetail{swis: _swis, sbl: _sbl, school_code: _school_code, deed_page: _deed_page,
land_assessed_value: _land_assessed_value, deed_book: _deed_book}
}
我用来调用它的Python代码:
from ctypes import cdll, c_uint32, Structure, c_char_p
class TaxDetail(Structure):
_fields_ = [('swis', c_char_p),
('sbl', c_char_p),
('school_code', c_char_p),
('land_assessed_value', c_uint32),
('deed_book', c_char_p),
('deed_page', c_char_p), ]
def __str__(self):
return str(self.swis)
lib = cdll.LoadLibrary(r"C:\Rust Workspace\embed\target\release\embed.dll")
lib.parse_details.restype = TaxDetail
lib.parse_details.argtype = (c_char_p,)
result = lib.parse_details(b"1346011 63 WAP WEST LLC 00000101 13460100615800142703690000 63 Wap West LLC 10 Fair Oaks Dr Poughkeepsie, NY 12603 000500000150000000017135601 14270369 411 000001 1 4-6Church St 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006158-14-270369-0000 058369006127002200002074000000052500000000286000N 0000000028600000000000000000000000000000000000Y")
print(result)
我已经对我的Rust代码添加了println!
次调用,并且当它尝试创建并返回结构时,似乎发生了访问冲突。我得到的具体错误信息是Process finished with exit code -1073741819 (0xC0000005)
。
在64位Windows 10上使用32位Rust和Python会发生这种情况。
答案 0 :(得分:3)
我不确定问题的全部范围,但我知道这个问题不会很好:你不能通过FFI返回String
。< / p>
Rust String
在概念上是3个部分:指向一块内存的指针,该内存有多长,以及该内存中有多少是有效字符串。
将其与C字符串进行比较。 C字符串只是指向内存的指针。你不知道有多少内存,你只知道每个字节走下去有效长度,直到你得到一个NUL字节。
更重要的是,String
未标记为#[repr(C)]
,因此String
结构的实际布局取决于Rust编译器。
我怀疑发生错误是因为Python看到你返回c_char_p
(我假设是char *
)。然后它尝试读取指针的数据,然后移动到下一个指针。它读取的“指针”可能是String
的指针或长度或容量,一旦它读取第二个指针它就会在杂草中关闭某处。
相反,您需要找出处理此字符串的其他方法。一些想法:
CString
并具有返回as_ptr
结果的方法。类似的逻辑适用于&str
,它在概念上是指向一块内存的指针以及该内存的多少有效。