【问题标题】:Cython: Cannot convert Python object to structCython:无法将 Python 对象转换为结构
【发布时间】:2014-09-22 19:22:44
【问题描述】:

警告:我是 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 (?!)

test.py:

import mytest

mytest.test()

当我输入: cython -a mytest.pyx 时,它说:“无法将 Python 对象转换为‘数据集’”, 指向 D = myiolib.readDataset("test.dat")。 为什么?我不明白...我做错了什么?

【问题讨论】:

    标签: python cython


    【解决方案1】:

    首先,我认为您的最小示例非常糟糕。您不包含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 编译不需要这个;这不会让我感到惊讶。尽管如此,你还是在使用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
    

    它有效。

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

    【讨论】:

    • 就是这样!非常感谢。很抱歉没有提供 setup.py。我完全忘记了! ://
    猜你喜欢
    • 2013-06-05
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多