python - Cython:无法将 Python 对象转换为结构

标签 python cython

警告:我是 Cython 的新手。 :D 我有以下代码:

my_structs.h:

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

myiolib.pyx:

from libc.stdlib cimport malloc
from libc.string cimport strcpy
from cpython.string cimport PyString_AsString

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


cdef Dataset readDataset(TID_name):
    cdef:
        int i, line_count=0
        Dataset instance

    with open(TID_name, 'rU') as file_iter:
        for line in file_iter:
            line_count=line_count+1

    instance.tid = <char **>malloc(line_count * sizeof(char *))

    i = 0
    with open(TID_name, 'rU') as file_iter:
        for line in file_iter:
            instance.tid[i] = <char *>malloc((len(line)+1) * sizeof(char ))
            strcpy(instance.tid[i], PyString_AsString(line.strip()))
            i += 1

    instance.lines = line_count
    return instance

mytest.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 mytest.pyx 时,它显示:“无法将 Python 对象转换为‘数据集’”, 指向 D = myiolib.readDataset(“test.dat”)。 为什么?我不明白...我做错了什么?

最佳答案

首先,我认为你的最小示例非常糟糕。您不包含 setup.py 或任何其他运行代码的方式。

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

test_python.py

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

import my_test

my_test.test()

my_test.pyx

import my_library

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

def test():
    cdef MyType my_instance
    my_object = my_library.my_function()

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 编译不需要这个;我不会感到惊讶。但即便如此,您在应该使用 cimport 的地方却使用了 import

添加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

并且它有效。

如果这些提示不能解决您的问题,请给我一个可以运行的示例。

关于python - Cython:无法将 Python 对象转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25970912/

相关文章:

python - Render_template 在 while 循环中更新

python - 让 pandas 打印完整的字符串

python - 加快Python时间戳到日期时间的转换

python - `cimport numpy` 使用 Cython 引发错误

python - Pandas 在 Mac OS X 上的安装 : ImportError (cannot import name hashtable)

kivy - Kivy 和 Buildozer 的问题

python - 我该怎么做才能知道 Beautifulsoup 中家长的类(class)名称?

python - Python中的未绑定(bind)本地错误

python - 加快 python pandas 中的 read_csv

python - 使用Cython加速连通分量算法