在cython中使用typedef'd结构

2024-05-19 05:06:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想把它导入cython,所以我有:

^{pr2}$

现在我想将内存分配给一个tadcm数组。我有以下内容:

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块之外定义了tadcm,那么代码编译就没有问题了。因此,如果我进口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 

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


Tags: 定义includecythonintheaderdoubleendiftheta
2条回答

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":
#                     ^^^
    [...]

可能是一个老的问题(或者太。。。β?)cython版本。在

我同意这不是一个真正的答案大部分是一个很长的评论。。。但我用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

相关问题 更多 >

    热门问题