Cython:无法将Python对象转换为stru

2024-10-02 20:29:59 发布

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

警告:我对Cython是个新手。:天 我有以下代码:

我的结构h:

typedef struct dataset{
    int lines;
    char **tid;
}Dataset;

在myiolib.pyx公司公司名称:

^{pr2}$

在我的测试.pyx公司名称:

import myiolib

cdef extern from "my_structs.h":
    cdef struct Dataset:
        int lines
        char **tid


def test():
    cdef Dataset D
    D = myiolib.readDataset("test.dat")

    # Do something...
    # Free memory (?!)

在测试.py公司名称:

import mytest

mytest.test()

当我输入:cython-a我的测试.pyx上面写着:“无法将Python对象转换为‘Dataset’, 指向D=myiolib.readDataset("测试数据"). 为什么?我不明白。。。我做错什么了?在


Tags: testimport名称公司datasetstructintlines
1条回答
网友
1楼 · 发布于 2024-10-02 20:29:59

首先,我认为你的小例子很糟糕。不包括setup.py或任何其他运行代码的方式。在

因此,这里有一个适当的最小示例:

test_python.py

import pyximport
pyximport.install(setup_args={'include_dirs': "."})

import my_test

my_test.test()

my_test.pyx

^{pr2}$

my_library.pyx

cdef extern from "my_type.h":
    cdef struct MyType:
        int x

cdef MyType my_function():
    return MyType()

my_type.h

typedef struct MyType {
    int my_attribute;
} MyType;

此错误包含:

AttributeError: 'module' object has no attribute 'my_function'

这是因为cdef正在使用,因此import将不允许访问该函数。你也用过cdef,所以我很惊讶你没有这样做。也许用setup.py编译并不需要这个;这不会让我感到惊讶。即使这样,您仍然在使用import,而您应该使用cimport。在

添加my_library.pxd

cdef extern from "my_type.h":
    cdef struct MyType:
        int x

cdef MyType my_function()

(可选)从pyx文件中删除cdef extern并更改

import my_library

cimport my_library

而且很管用。在

如果这些技巧不能解决你的问题,请给我一个我可以运行的例子。在

相关问题 更多 >