Skip to main content
 首页 » 编程设计

python之在 cython 函数中使用 python ctypes 数组数据

2025年01月19日9bhlsheji

我有 python ctypes 数组。我想在 cython def 和 cdef 函数中使用它。

import ctypes 
from my_cython_extention import * 
 
class Test_Node(ctypes.Structure): 
    _fields_ = [ 
        ("i", ctypes.c_int), 
        ("f", ctypes.c_float), 
    ] 
my_array = (Test_Node * 10)() 
my_cython_function(my_array) 

我应该如何定义 cython 函数 my_cython_function 来访问 my_array 数据?我可以获取 my_array C++ 数据指针吗?

请您参考如下方法:

我找到了问题的答案:

cdef my_cython_function_c( 
    Test_Node *arr_addr, int arr_size 
): 
    for i in range(arr_size): 
        printf("%i\n", arr_addr.i) 
        inc(arr_addr) 
 
def my_cython_function(arr): 
    my_cython_function_c(<Test_Node *><long>ctypes.addressof(arr), len(arr))