【发布时间】:2015-08-31 14:07:44
【问题描述】:
我有一个 Rust 库,需要通过 ctypes 模块导入 Python。我的目标是使用以 Vec<T> / i32 作为参数并从 Python 返回这些类型的 Rust 函数。目前,我可以将整数传递给 Rust 函数,并让它们返回列表/整数。这是当前代码:
Python:
import ctypes
from ctypes import cdll
class List_4(ctypes.Structure):
_fields_ = [("array", ctypes.ARRAY(ctypes.c_int32, 4))]
rust = cdll.LoadLibrary("target/debug/py_link.dll")
rust.function_vec.restype = List_4
foobar = rust.function_i32(5)
barbaz = rust.function_vec([1, 2, 3, 4]) # Throws error: Don't know how to convert parameter
print foobar
print barbaz
生锈:
#[repr(C)]
pub struct List_4 {
array: [i32; 4]
}
#[no_mangle]
pub extern fn function_i32(number: i32) -> i32 {
number
}
#[no_mangle]
pub extern fn function_vec(list: List_4) -> List_4 {
List_4 { array: [1, 2, 3, 5] }
}
我需要帮助的是将 Python 列表作为参数传递给 Rust 函数。我最好的猜测是将 ctypes.ARRAY 传递给函数而不是列表,但我不确定如何将 Python 列表转换为该类型。
注意:我尝试了来自 this related question 的 Rust 代码,但是当我尝试编译它时,它显示“与 `gcc` 链接失败:退出代码:1”和“错误的 reloc 地址”。
【问题讨论】:
-
这个问题能碰吗?现在没有人会看到它,我宁愿让人们回答这个问题,而不是一个新问题。
-
是的,我在 Windows 上。谢谢你让我知道,我可以做任何一个,但使用数组会更容易。但是,制作具有我认为容量的向量并不会太难,所以如果我可以将数组传递给函数,它可以进行转换。如果我错了,请纠正我。