【问题标题】:How to access arrays passed to ctypes callbacks as numpy arrays?如何访问作为 numpy 数组传递给 ctypes 回调的数组?
【发布时间】:2013-10-31 09:11:58
【问题描述】:

我正在尝试使用 numpy 和 ctypes 将一些用 C 编写的数字代码集成到 Python 库中。我已经进行了实际计算,但现在想将我的算法中间步骤的进度报告给我的 Python 代码中的回调函数。虽然我可以成功调用回调函数,但我无法检索传递给回调的x 数组中的数据。在回调中,x 是一个 ndpointer 对象,我似乎无法取消引用。

当前代码

考虑这个最小的例子:

test.h:

typedef void (*callback_t)(
    double *x,
    int n
);

void callback_test(double* x, int n, callback_t callback);

test.c:

#include "test.h"

void callback_test(double* x, int n, callback_t callback) {
    for(int i = 1; i <= 5; i++) {

        for(int j = 0; j < n; j++) {
            x[j] = x[j] / i;
        }

        callback(x, n);
    }
}

test.py:

#!/usr/bin/env python

import numpy as np
import numpy.ctypeslib as npct
import ctypes
import os.path

array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')

callback_func = ctypes.CFUNCTYPE(
    None,            # return
    array_1d_double, # x
    ctypes.c_int     # n
)

libtest = npct.load_library('libtest', os.path.dirname(__file__))
libtest.callback_test.restype = None
libtest.callback_test.argtypes = [array_1d_double, ctypes.c_int, callback_func]


@callback_func
def callback(x, n):
    print("x: {0}, n: {1}".format(x, n))


if __name__ == '__main__':
    x = np.array([20, 13, 8, 100, 1, 3], dtype=np.double)
    libtest.callback_test(x, x.shape[0], callback)

电流输出

编译并运行脚本后,我得到以下输出:

x: <ndpointer_<f8_1d_CONTIGUOUS object at 0x7f9b55faba70>, n: 6
x: <ndpointer_<f8_1d_CONTIGUOUS object at 0x7f9b55faba70>, n: 6
x: <ndpointer_<f8_1d_CONTIGUOUS object at 0x7f9b55faba70>, n: 6
x: <ndpointer_<f8_1d_CONTIGUOUS object at 0x7f9b55faba70>, n: 6
x: <ndpointer_<f8_1d_CONTIGUOUS object at 0x7f9b55faba70>, n: 6

我也尝试过子集运算符x[0:n] (TypeError: 'ndpointer_x.value (将指针作为数字返回)。

黑客解决方案

如果我使用callback_func 的以下替代定义:

callback_func = ctypes.CFUNCTYPE(
    None,            # return
    ctypes.POINTER(ctypes.c_double), # x
    ctypes.c_int     # n
)

以及以下替代回调函数:

@callback_func
def callback(x, n):
    print("x: {0}, n: {1}".format(x[:n], n))

我得到了想要的结果:

x: [20.0, 13.0, 8.0, 100.0, 1.0, 3.0], n: 6
x: [10.0, 6.5, 4.0, 50.0, 0.5, 1.5], n: 6
x: [3.3333333333333335, 2.1666666666666665, 1.3333333333333333, 16.666666666666668, 0.16666666666666666, 0.5], n: 6
x: [0.8333333333333334, 0.5416666666666666, 0.3333333333333333, 4.166666666666667, 0.041666666666666664, 0.125], n: 6
x: [0.16666666666666669, 0.10833333333333332, 0.06666666666666667, 0.8333333333333334, 0.008333333333333333, 0.025], n: 6

我的问题

在回调中访问x 是否有更 numpy-ish 的方式?与其下标然后转换回numpy.array,我更愿意访问ndpointer指向的数据,因为我想限制x的副本数量(为了优雅的代码)

如果你想试验我的代码,我有整个小例子的uploaded a gist

【问题讨论】:

    标签: python numpy ctypes


    【解决方案1】:

    我找到了使用 ctypes.POINTER(ctypes.c_double)numpy.ctypeslib.as_array 的解决方案 - 根据 numpy.ctypeslib 文档,这将与数组共享内存:

    callback_func = ctypes.CFUNCTYPE(
        None,            # return
        ctypes.POINTER(ctypes.c_double), # x
        ctypes.c_int     # n
    )
    

    [...]

    @callback_func
    def callback(x, n):
        x = npct.as_array(x, (n,))
        print("x: {0}, n: {1}".format(x, n))
    

    任何人有更优雅的解决方案,也许使用ndpointer 对象?

    【讨论】:

    • ctypeslib.as_array 允许您在创建 NumPy 数组时指定 shape。代价是它必须为每个指针实例准备数组接口;但是,它确实将其缓存为 ctypes 数组类型上的 property
    • ndpointer 创建_ndptr 的子类,它是c_void_p 的子类,具有NumPY __array_interface__。它使用 ctypes from_param 对函数指针参数进行类型验证,然后转至 obj.ctypes。它使用 ctypes _check_retval_restype 创建一个数组;这将返回一个 NumPy 数组副本(您可以对其进行修补以使用 copy=False)并需要一个定义 shape 元组的数组接口。如果你已经定义了shape,你可以在回调中使用x = np.array(x, copy=False)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2023-03-24
    • 2012-01-15
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多