我正在尝试使用 numpy 和 ctypes 将一些用 C 编写的数字代码集成到 Python 库中。我已经开始进行实际计算,但现在想将算法中间步骤的进度报告给 Python 代码中的回调函数。虽然我可以成功调用回调函数,但无法检索x
数组传递给回调。在回调中,x
is an 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]
(类型错误:'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
我的问题
有没有更 numpy 式的访问方式x
在回调中?而不是下标然后转换回numpy.array
,我更愿意访问 ndpointer 指向的数据,因为我想限制 ndpointer 的副本数量x
(并且为了优雅的代码)
I've 上传了要点 https://gist.github.com/sseemayer/7246463如果您想在我的代码上进行实验,请查看整个迷你示例。