Cython“无法为cdef类、结构或联合中的字段指定默认值”

2024-10-02 12:23:34 发布

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

我第一次尝试将Python代码移植到Cython。我在C方面的经验非常有限。我正在尝试创建一个相对简单的类来存储多维数组。对于这个问题,让我们将其留给一个长度为1的一维数组作为属性time。目前,我收到错误信息:

    cdef np.ndarray[np.int64_t, ndim=1] time = np.empty([1], dtype=np.int64)
                                       ^
------------------------------------------------------------
data.pyx:22:40: Cannot assign default value to fields in cdef classes, structs or unions

以下是最相关的文件

data.pyx

import numpy as np
cimport numpy as np


cdef extern from "data_extern.h":

    cppclass _Data "Data":

        np.int64_t time64[1]
        double x_coord, y_coord, z_coord
        _Data(np.int64_t *time, double x, double y, double z)


cdef class Data:

    cdef _Data *thisptr
    cdef np.ndarray[np.int64_t, ndim=1] time = np.empty([1], dtype=np.int64)

    def __cinit__(self, np.int64_t time[1], x, y, z):
        self.thisptr = new _Data(&time[0], x, y, z)

    def __dealloc__(self):
        del self.thisptr

数据_extern.h

#ifndef DATA_EXTERN_H
#define DATA_EXTERN_H

class Data {
    public:
        signed long long time64[1];
        double x_coord, y_coord, z_coord;
        Data();
        Data(signed long long time[1], double x, double y, double z;
        ~Data();
};

#endif

数据_extern.cpp

#include <iostream>
#include "data_extern.h"

Data::Data () {}

// Overloaded constructor
Data::Data (signed long long time[1], double x, double y, double z {
    this->time64 = time[0];
    this->x_coord = x;
    this->y_coord = y;
    this->z_coord = z;
}

// Destructor
Data::~Data () {}

我承认我的代码可能存在多个问题,但如果有人能解释错误消息,我将不胜感激


Tags: selfdatatimenpexternthislongdouble
1条回答
网友
1楼 · 发布于 2024-10-02 12:23:34

问题如错误消息中所述:无法为cdef类的C级属性设置默认值。您可以通过如下设置__cinit__构造函数中的值来解决此问题:

cdef class Data:
    cdef _Data *thisptr
    cdef np.ndarray[np.int64_t, ndim=1] time

    def __cinit__(self, np.int64_t time[1], x, y, z):
        self.thisptr = new _Data(&time[0], x, y, z)
        self.time = np.empty([1], dtype=np.int64)

    def __dealloc__(self):
        del self.thisptr

不过,总而言之,整个np.ndarray语法已经过时了。除非你已经死掉地使用NUMPY类型(因为在与C++类库接口时,代码中不必要),所以可以使用更现代的typed memoryview语法。您可以使用from libc.stdint cimport *导入大小的整数类型,以使用这些类型而不是numpy类型

相关问题 更多 >

    热门问题