使用 cffi,我试图在 Python 代码中调用一些 Rust 函数。这是python代码:
from cffi import FFI
def rust(solution):
ffi = FFI()
lib = ffi.dlopen("./libnorm.so")
ffi.cdef('float norm(float**)')
return lib.norm(solution)
solution = [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6]]
print(rust(solution))
这是锈代码:
#! [crate_type = "dylib"]
#[no_mangle]
pub extern fn norm(array: Vec< Vec<f64>>) -> f64 {
return array.len() as f64
}
我编译了这个库:
rustc --crate-type=dylib norm.rs
但是当我运行我的 python 脚本时,我得到了这个堆栈:
Traceback (most recent call last):
File "/usr/lib64/python3.5/site-packages/cffi/cparser.py", line 260, in _parse
ast = _get_parser().parse(csource)
File "/usr/lib/python3.5/site-packages/pycparser/c_parser.py", line 151, in parse
debug=debuglevel)
File "/usr/lib/python3.5/site-packages/pycparser/ply/yacc.py", line 331, in parse
return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
File "/usr/lib/python3.5/site-packages/pycparser/ply/yacc.py", line 1181, in parseopt_notrack
tok = call_errorfunc(self.errorfunc, errtoken, self)
File "/usr/lib/python3.5/site-packages/pycparser/ply/yacc.py", line 193, in call_errorfunc
r = errorfunc(token)
File "/usr/lib/python3.5/site-packages/pycparser/c_parser.py", line 1723, in p_error
self._parse_error('At end of input', self.clex.filename)
File "/usr/lib/python3.5/site-packages/pycparser/plyparser.py", line 55, in _parse_error
raise ParseError("%s: %s" % (coord, msg))
pycparser.plyparser.ParseError: : At end of input
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 35, in <module>
print(rust(solution))
File "main.py", line 28, in rust
ffi.cdef('float norm(float**)')
File "/usr/lib64/python3.5/site-packages/cffi/api.py", line 105, in cdef
self._cdef(csource, override=override, packed=packed)
File "/usr/lib64/python3.5/site-packages/cffi/api.py", line 119, in _cdef
self._parser.parse(csource, override=override, **options)
File "/usr/lib64/python3.5/site-packages/cffi/cparser.py", line 299, in parse
self._internal_parse(csource)
File "/usr/lib64/python3.5/site-packages/cffi/cparser.py", line 304, in _internal_parse
ast, macros, csource = self._parse(csource)
File "/usr/lib64/python3.5/site-packages/cffi/cparser.py", line 262, in _parse
self.convert_pycparser_error(e, csource)
File "/usr/lib64/python3.5/site-packages/cffi/cparser.py", line 291, in convert_pycparser_error
raise api.CDefError(msg)
cffi.api.CDefError: parse error
: At end of input
我错过了什么吗?
我尝试了几个版本:ffi.cdef('float norm(float**)')
. 喜欢ffi.cdef('float norm(Vec< Vec<float>>)')
或ffi.cdef('float norm(float[][])')
但它也不起作用。
感谢您以后的回复。