【问题标题】:Wrapping c-function in Python with ctypes在 Python 中使用 ctypes 包装 c 函数
【发布时间】:2017-07-22 01:20:06
【问题描述】:

我有一个带有以下签名的 c 函数

__declspec( dllexport ) void* setup(int c_force, int c_stepping, int c_iteration, int c_roots,
                                    struct para* c_userdata, double* c_y0,
                                    double c_reltol, double c_abstol)
{
    ....
    return "a pointer";
}

其中 para 定义如下。我想用这个函数(和其他函数)构建一个 dll 并从 Python 访问它。重要的 Python 行是

import ctypes as ct
lib = ct.cdll.LoadLibrary('lib_path.dll')
getattr(lib, 'setup')
lib.setup.restype = ct.c_void_p
# pystruct as defined below to avoid clogging code
lib.setup.argtypes = [ct.c_int, ct.c_int, ct.c_int, ct.c_int,
                      ct.POINTER(para), ct.POINTER(ct.c_double),
                      ct.c_double, ct.c_double]
ptr = lib.setup(cf, cs, ci, cr, ct.byref(para), c_y0, c_reltol, c_abstol) 
myobj = ct.c_void_p(ptr)

其中cfcscicr 是 (python) 整数,para 是如下定义的结构类型,c_y0=(ct_c_double * 2)()(长度应为 2,均来自 python侧和 c 侧)和 c_reltolc_abstol 被转换为 ct.c_double 为 c_reltol = ct.c_double(reltol)

当我尝试运行我的主应用程序时,我在lib.setup-函数调用中得到WindowsError: exception: access violation writing xxx,但我不明白为什么...在调用lib.setup 之前打印会给出以下值和类型的输出传递给函数的参数(按顺序)

1 2 2 1 <cparam 'P' (0000000003C84EB0)> <cvode_library.c_double_Array_2 object at 0x0000000003F95BC8> c_double(1e-06) c_double(1e-08)

<type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'CArgObject'> <class 'cvode_library.c_double_Array_2'> <class 'ctypes.c_double'> <class 'ctypes.c_double'>

我一直在尝试使用thisthis 问题进行调试,但没有成功。由于 c 函数的调用签名相当简单,我不明白它为什么会中断。

附:它在 Ubuntu 上完美运行,__declspec... 替换为 extern

c-struct 定义为

typedef struct para PARA;
struct para
{
    double a;
    double b;
    double c;
};

和对应的pystruct为

class para(ct.Structure):
    _fields_ = [('a', ct.c_double),
               ('b', ct.c_double),
               ('c', ct.c_double)]

编辑 c_y0 定义为

y0 = np.array([0., 0.])
c_y0 = (ct.c_double * 2)()
c_y0[0] = y0[0]
c_y0[1] = y0[1]

所有“cvode”函数和N_Vector 都是Sundials suite for solving nonlinear equations 的一部分

__declspec( dllexport ) void* setup(int c_force, int c_stepping, int c_iteration, int c_roots,
                                    struct para* c_userdata, double* c_y0,
                                    double c_reltol, double c_abstol)
{
    int flag;
    N_Vector y;
    void* cvode_mem;
    PARA* ptr_para;
    ptr_para = c_userdata;

    // ****** Set up vector with initial conditions ******
    y = N_VNew_Serial(2);
    NV_Ith_S(y,0) = c_y0[0];
    NV_Ith_S(y,1) = c_y0[1];

    // ****** Create cvode object with stepping and iteration method ******
    if(c_iteration==CV_FUNCTIONAL)
        cvode_mem = CVodeCreate(c_stepping, 1);    // Functional iteration
    else
        cvode_mem = CVodeCreate(c_stepping, 2);    // Newton interation
    if(check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(NULL);

    flag = CVodeInit(cvode_mem, ode, 0, y);

    if(check_flag(&flag, "CVodeInit", 1)) return(NULL);

    // ****** Specify integration tolerances ******
    flag = CVodeSStolerances(cvode_mem, c_reltol, c_abstol);
    if(check_flag(&flag, "CVodeSStolerances", 1)) return(NULL);

    // ****** Set up linear solver module if required ******
    if(c_iteration==CV_DENSE_USER)
    {
        printf("Dense user supplied Jacobian\n");
        // Dense user-supplied Jacobian
        flag = CVDense(cvode_mem, 2);
        if(check_flag(&flag, "CVDense", 1)) return(NULL);

        flag = CVDlsSetDenseJacFn(cvode_mem, jac);

        if(check_flag(&flag, "CVDlsSetDenseJacFn", 1)) return(NULL);
    }
    else if(c_iteration==CV_DENSE_DQ)
    {
        // Dense difference quotient Jacobian
        flag = CVDlsSetDenseJacFn(cvode_mem, NULL);
        if(check_flag(&flag, "CVDlsSetDenseJacFn", 1)) return(NULL);
    }


    // Set optional inputs
    flag = CVodeSetUserData(cvode_mem, c_userdata);
    if(check_flag(&flag, "CVodeSetUserData", 1)) return(NULL);

    // Attach linear solver module

    // Specify rootfinding problem
    if(c_roots!=ROOTS_OFF)
    {
         flag = CVodeRootInit(cvode_mem, 1, root_func);
    }

    return cvode_mem;
}

【问题讨论】:

  • 您能否分享整个代码(尤其是setup func),让我们决定什么是重要的?或更好:尝试将您的代码减少到[SO]: mcve。我很担心c_y0
  • @CristiFati 我知道 mcve 将是最佳的,但代码非常大,因此隔离它会有点棘手。如果绝对有必要,我明天可以尝试这样做。但是请参阅编辑以获取格式良好的setup-function。
  • 很抱歉,有太多变量可能出错,还有太多我没有的额外信息。所以你可以考虑mcve。顺便说一句:NV_Ith_S 是一个宏,对吗?当您尝试访问“不属于您的”内存时会发生访问冲突
  • 我完全理解你,所以感谢你的时间。我今天一整天都在纠结这个问题。奇怪的是,相同的代码在 Ubuntu 上运行完美。我不是 100% 确定 NV_Ith_S 到底是什么,但它是日晷库的一部分。不过再次感谢!
  • 我确定我们所说的是UB(未定义的行为)。它在某些情况下适用于某些编译器,否则会失败。它在某些情况下有效的事实应该被认为是(愚蠢的)运气。最近,我遇到了一种情况,当数组越界 someArray[-1] 在许多 Ux总是完美地工作(虽然它应该有 segfault ed),但在 Win 总是抛出 Access Violation.

标签: python c ctypes


【解决方案1】:

这是一个 MCVE。它表明您的声明是正确的,因此问题可能出在函数实现中。如果以下方法不适合您,请使用可重现您的失败的类似 MCVE 更新您的问题。

test.c

#include <stdio.h>

typedef struct para PARA;
struct para
{
    double a;
    double b;
    double c;
};

__declspec(dllexport) void* setup(int c_force, int c_stepping, int c_iteration, int c_roots,
                                  struct para* c_userdata, double* c_y0,
                                  double c_reltol, double c_abstol)
{
    printf("%d %d %d %d %lf %lf %lf %lf %lf %lf %lf\n",c_force,c_stepping,c_iteration,c_roots,c_userdata->a,c_userdata->b,c_userda
ta->c,c_y0[0],c_y0[1],c_reltol,c_abstol);
    return NULL;
}

test.py

import ctypes as ct

class para(ct.Structure):
    _fields_ = [('a', ct.c_double),
               ('b', ct.c_double),
               ('c', ct.c_double)]

lib = ct.CDLL('test')
lib.setup.restype = ct.c_void_p
# pystruct as defined below to avoid clogging code
lib.setup.argtypes = [ct.c_int, ct.c_int, ct.c_int, ct.c_int,
                      ct.POINTER(para), ct.POINTER(ct.c_double),
                      ct.c_double, ct.c_double]
p = para(1.5,2.5,3.5)
c_y0 = (ct.c_double * 2)(4.5,5.5)
ptr = lib.setup(1,2,3,4,p, c_y0,6.5,7.5) 
myobj = ct.c_void_p(ptr)

输出

1 2 3 4 1.500000 2.500000 3.500000 4.500000 5.500000 6.500000 7.500000

【讨论】:

  • 感谢 Mark 提供的清晰示例,它确实有效。经过更多调试后,我发现不是函数调用本身发生故障(如您的示例所示),而是对 cvode-function NV_Ith_S(y,i) = c_y0[i]; 的调用。如果我注释掉这些行,设置就可以工作,但对他们来说就不行。我怀疑某些东西与我的库不兼容,目前调试它感觉超出了范围。但是再次感谢您的示例!
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多