python - 在 cython 中使用 typedef'd 结构

标签 python c typedef cython

我在头文件 dcm.h 中有以下定义:

typedef struct
{    
    double alpha;
    double gamma;
    double tau;
} ThetaDCM;

我想将它导入到 cython 中,所以我有:

cdef extern from "dcm.h":

    ctypedef struct ThetaDCM:

        np.float64_t alpha
        np.float64_t gamma
        np.float64_t tau

现在我想为 ThetaDCM 数组分配内存。我有以下内容:

cdef ThetaDCM *c_theta = <ThetaDCM *> malloc(nt * nb * sizeof(ThetaDCM))

free(c_theta)

这没有编译并报告以下错误:

error: ‘ThetaDCM’ undeclared (first use in this function)
   __pyx_v_c_theta = ((ThetaDCM *)malloc(((__pyx_v_nt * __pyx_v_nb) * (sizeof(ThetaDCM)))));

还有与此相关的其他错误。如果我在 extern block 之外定义 ThetaDCM,则代码编译不会出现问题。因此,如果我导入 Theta,cython 将看不到我的声明。有没有标准的方法来解决这个问题?

编辑:

我的文件标题比我发布的要复杂一些。这是

# ifdef __CUDACC__
# ifndef DDM_HEADER
# define DDM_HEADER

#include "math.h"
#include "curand_kernel.h"
#include "curand.h"
#include <stdio.h>
...
# endif 

# ifdef __CUDACC__
# define BDDM_EXTERN extern "C"
# else
# define BDDM_DEVICE
# endif

BDDM_EXTERN
int llh_m0t( double *x, double *y, double *u,
    double *theta, double *ptheta, int ny, int nt, double *llh);
...
typedef struct
{    
    double alpha;
    double gamma;
    double tau;
} ThetaDCM;

# endif 

上面的指令用于检查编译器是否为 nvcc(cuda 代码的编译器)。现在我意识到有一个错误,我应该这样做:

# ifndef DDM_HEADER
# define DDM_HEADER
# ifdef __CUDACC__

#include "math.h"
#include "curand_kernel.h"
#include "curand.h"
#include <stdio.h>
...
# endif

BDDM_EXTERN
int llh_m0t( double *x, double *y, double *u,
    double *theta, double *ptheta, int ny, int nt, double *llh);
...

typedef struct
{    
    double alpha;
    double gamma;
    double tau;
} ThetaDCM;
# endif 

令我困惑的是,尽管 # ifdef CUDACCcython 代码还是编译了。我使用 cython 来包装第一个 #ifdef 语句中定义的 c 函数(如 llh_m0t),因此令人困惑的是 cython 可以看到这些函数定义。

最佳答案

Cython 不提供对 #define 宏的支持,以便按照 header 的要求进行条件编译:

dcm.h

# ifdef __CUDACC__

typedef struct
{    
    double alpha;
    double gamma;
    double tau;
} ThetaDCM;

# endif

快速解决方法:

dcm.pyh

#define __CUDACC__
#include "dcm.h"


dcm.pyx

[...]

cdef extern from "dcm.pyh":
#                     ^^^
    [...]

关于python - 在 cython 中使用 typedef'd 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544587/

相关文章:

python - 没有名为 pytesseract 的模块错误

c++ - 在 C++ 中使用 const ArrayType 或 ConstArrayType typedef 具有 const 元素的数组

c++ - 为什么 std::function 作为 std::not2 的参数?

c - 串行通信重置/etc/profile (linux)

objective-c - 为什么在 C 中将大 double 转换为 long 有时会返回正值而有时会返回负值?

c++ - 为 typedef 定义的对象添加 ofstream 方法

python - 如何制作带有未定义区域的彩色图?

python - 如何使用 django_graphene 解析 django 模型的自定义字段?

python - Pandas - 合并不同大小的数据帧

c - 如何验证作为 void 指针传递给函数的值的类型?