将Python列表传递给Rust函数
我有一个Rust库,需要通过ctypes模块导入Python。我的目标是使用Rust函数,这些函数将将Python列表传递给Rust函数,python,rust,ffi,Python,Rust,Ffi,我有一个Rust库,需要通过ctypes模块导入Python。我的目标是使用Rust函数,这些函数将Vec/i32作为参数,并从Python返回这些类型。目前,我可以将整数传递给Rust函数,并让它们返回列表/整数。以下是当前代码: Python: 导入ctypes 从ctypes导入cdll 类列表4(ctypes.Structure): _字段=[(“数组”,ctypes.array(ctypes.c_int32,4))] rust=cdll.LoadLibrary(“target/debu
Vec
/i32
作为参数,并从Python返回这些类型。目前,我可以将整数传递给Rust函数,并让它们返回列表/整数。以下是当前代码:
Python:
导入ctypes
从ctypes导入cdll
类列表4(ctypes.Structure):
_字段=[(“数组”,ctypes.array(ctypes.c_int32,4))]
rust=cdll.LoadLibrary(“target/debug/py_link.dll”)
rust.function\u vec.restype=List\u 4
foobar=rust.function_i32(5)
barbaz=rust.function_vec([1,2,3,4])#抛出错误:不知道如何转换参数
打印foobar
打印barbaz
锈蚀:
#[repr(C)]
发布结构列表4{
数组:[i32;4]
}
#[没有损坏]
发布外部功能\u i32(编号:i32)->i32{
数
}
#[没有损坏]
发布外部功能(列表:列表4)->列表4{
列表4{数组:[1,2,3,5]}
}
我需要的帮助是将Python列表作为参数传递给Rust函数。我的最佳猜测是将ctypes.ARRAY
传递给函数而不是列表,但我不确定如何将Python列表转换为该类型
注意:我尝试了来自的Rust代码,但当我尝试编译它时,它显示“链接`gcc`失败:退出代码:1”和“错误的重新链接地址”。看起来我解决了这个问题。我将Python列表转换为C数组,并将其传递给Rust函数。以下是工作代码:
#[repr(C)]
发布结构列表4{
//使用#[repr(C)]创建一个结构,在Python中也会这样做,因此它是可共享的
数组:[i32;4]
}
#[没有损坏]
pub extern fn函数数组(列表:列表4)->列表4{
//返回列表4的新实例
列表4{数组:[1,2,3,5]}
}
Python:
有没有可能碰到这个问题?现在没有人会看到它,我宁愿让人们回答这个问题,而不是一个新问题。是的,我在Windows上。谢谢你让我知道,我也可以这样做,但是使用数组会更容易。然而,我认为,创建一个具有容量的向量并不太困难,因此,如果我可以将数组传递给函数,它就可以进行转换。如果我错了,请纠正我。
import ctypes # By using ctypes, and #[repr(C)], we use the same type
# of data in both languages, so it is possible to send stuff between them
rust = cdll.LoadLibrary("target/debug/py_link.dll") # Import the Rust dll
class List_4(ctypes.Structure):
# Similar to creating the struct in Rust
_fields_ = [("array", ctypes.ARRAY(ctypes.c_int32, 4))]
rust.function_array.restype = List_4 # Set the function's return type to List_4
def function_array(arr):
# For convenience, a function to convert a list to a C array, call the function,
# and convert its return value to a list
return list(
rust.function_array(
(ctypes.c_int * len(lst))(*lst) # Call the function after converting the list
).array
)
# To use the function:
>>> function_array([1, 2, 3])
[1, 2, 3, 5]