[英]Using typedef'd struct in 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块之外定义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 CUDACC,但是仍编译了cython代码。 我用cython封装了在第一个#ifdef语句(如llh_m0t)中定义的c函数,所以令人困惑的是cython可以看到这些函数定义。
cython的旧版本(也可能是beta版本)可能是一个问题。
我同意这并不是一个真正的答案-大多是一个很长的评论...但是使用cython 0.20.0对我有用 :
dcm.h
typedef struct { double alpha; double gamma; double tau; } ThetaDCM;
dcm.pyx
cimport numpy as np from libc.stdlib cimport malloc, free nt = 1 nb = 1 cdef extern from "dcm.h": ctypedef struct ThetaDCM: np.float64_t alpha np.float64_t gamma np.float64_t tau cdef ThetaDCM *c_theta = <ThetaDCM *> malloc(nt * nb * sizeof(ThetaDCM)) print(hex(<long>c_theta)) free(c_theta)
sh$ cython dcm.pyx
sh$ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I../include/python3.4m/ -L../lib/python3.4/ dcm.c -o dcm.so
sh$ python3Python 3.4.1 (default, Aug 20 2014, 14:47:11)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dcm
0x23e44f0
Cython不为标题所要求的条件编译提供#define
宏支持:
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": # ^^^ [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.