Cython - 包含从C到python结构的指针

时间:2016-02-24 13:01:24

标签: cython

我有一个C函数,它接受指向struct的指针,我希望通过Cthon Exthon的Cython方式在python中使用它但是当我想从python传递指向struct的时候给我一个错误:“无法将Python对象转换为'Foo *'“ 在下面的例子中,我使对象调用C函数,但传递给C函数的是NULL指针。

我的审判:

hello.h

#include <stdio.h>

typedef struct
{
    int x;
} Foo;

int hello(Foo* what);

的hello.c

#include "hello.h"

int hello(Foo* what)
{
    printf("Hello Wrapper\n");
    printf("what: %p\n", what);
    what->x = 5;
    return what->x;
}

phello.pxd

cdef extern from "hello.h":
    ctypedef struct Foo:
        int x

    cdef int hello(Foo* what)

phello.pyx

cimport phello

cdef class Foo_c:
    cdef phello.Foo* s

    def hello_fn(self):
        return phello.hello(self.s)

setup.py

from distutils.core import setup, Extension
from Cython.Distutils import build_ext

setup(
cmdclass = {'build_ext': build_ext},
ext_modules=[ Extension("hellomodule",
                         sources=["phello.pyx", "hello.c"],
                       ) ]

test.py

import hellomodule

print "Hello test.py"

tobject = hellomodule.Foo_c()
print "Object:", tobject

tobject.hello_fn()

所以我想在“test.py”中创建“Foo”结构并将其传递给“hello_fn()”函数以在传递此结构后调用C函数“hello()”,这样我就可以读取或写入双面结构python&amp;下进行。

请问有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您的代码不为phello.Foo分配内存。可以使用calloc(或malloc)在__cinit__中完成分配,并在__dealloc__中免费重新分配。

cimport phello
from libc.stdlib cimport calloc, free

cdef class Foo_c:
    cdef phello.Foo* s

    def __cinit__(self, int n):
        self.s = <phello.Foo *>calloc(1, sizeof(phello.Foo))

    def __dealloc__(self):
        free(<void *>self.s)

    def __init__(self, int n):
        self.s.x = n