Pass Python list to embedded Rust function

后端 未结 2 1292
粉色の甜心
粉色の甜心 2020-12-06 06:34

I am learning how to embed Rust functions in Python, and everything works fine if my inputs are ints, but not list.

If my lib.rs file is:<

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 06:43

    ctypes is about C bindings and in C there's no such a thing as a dynamic array.

    The closest object you can pass to a C function is a pointer to integer that however is not a dynamic array because

    1. It doesn't carry the size information
    2. You cannot grow or shrink the area, just access existing elements

    A simple alternative to passing pointers (and being very careful about not getting past the size) you could use instead is a function-based API.

    For example:

    getNumberOfThings() -> number
    getThing(index) -> thing
    

    but the Python code would then become like

    def func():
        n = getNumberOfThings()
        return [getThing(i) for i in range(n)]
    

    The counterpart (passing a variable number of elements) would be

    def func2(L):
        setNumberOfThings(len(L))
        for i, x in enumerate(L):
            setThing(i, x)
    

提交回复
热议问题