【问题标题】:Using cffi function with scipy.integrate.nquad将 cffi 函数与 scipy.integrate.nquad 一起使用
【发布时间】:2018-07-11 04:47:18
【问题描述】:

我无法使 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*)。

【问题讨论】:

    标签: scipy python-cffi


    【解决方案1】:

    文档讨论了接受 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)
    

    【讨论】:

    • 谢谢,我会试验并报告我的发现。
    猜你喜欢
    • 2020-09-13
    • 2019-12-20
    • 2019-10-26
    • 2017-06-16
    • 2021-10-25
    • 2014-08-05
    • 2017-06-25
    • 2015-06-29
    • 2020-09-09
    相关资源
    最近更新 更多