在 scipy.integrate.nquad 中使用 cffi 函数

Using cffi function with scipy.integrate.nquad

我无法使 scipy.integrate.nquad 使用 cffi 函数。 我也找不到任何在线示例。

假设我的 test.py

中有一个简单的 c 函数
ffibuilder.set_source("_test",     
    r""" #include <math.h>
        double test(int n, double* xx) {
            return xx[0]*xx[1];
        }
     """)

我正在尝试将它集成到第二个文件中 test_cffi.py,就像这样

from _test import ffi, lib
from scipy.integrate import nquad

xx = ffi.new("double[]",2)
xx[0] = 1
xx[1] = 2
# This works.
print(lib.test(2,xx))
# This I can't make to work
print(nquad(lib.test3,[[0,1],[0,1]],args=(2,)))

在上面的最后一行我应该怎么做才能使集成工作? Scipy 文档说函数签名必须是 double f(int, double*)。

文档讨论了接受 ctypes 函数,它可能在 nquad() 中是特殊情况。它没有提到 cffi 函数,这意味着没有对此的特殊支持。

您可以尝试获取 C 级函数的地址并将其手动包装在 ctypes 函数中,以便 nquad() 再次解包并直接调用 C 函数:

raw_addr = int(ffi.cast("intptr_t", ffi.addressof(lib, "test")))
CF = ctypes.CFUNCTYPE(ctypes.c_double,
         ctypes.c_int, ctypes.POINTER(ctypes.c_double))
wrapper_function = CF(raw_addr)