将python对象转换为cython指针

将python对象转换为cython指针

本文介绍了将python对象转换为cython指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用cython将c ++类公开给python.我在* .pxd文件中编写了它们的定义,并在* .pyx文件中实现了包装器.但是我在尝试传递给扩展类型的函数指针时遇到了麻烦.这是简化的示例.

I'm trying to expose c++ classes to python using cython. I wrote their definitions in *.pxd file and implemented a wrappers in *.pyx files. But I got stuck trying to pass to a function pointer to the extension type. Here is simplified example.

foo.pyx

from c_foo cimport cFoo
cdef class Foo:
    cdef cFoo* _impl

c_foo_holder.pxd

cdef extern from "FooHolder.h":
    cdef cppclass cFooHolder:
        cFooHolder(cFoo* foo)

foo_holder.pyx

from c_foo_holder cimport cFooHolder
from c_foo cimport cFoo

cdef class FooHolder:
    cdef cFooHolder* _impl
    def __init__(self, foo):
        self._impl = new cFooHolder(<cFoo*>(foo._impl)) # error here

但是在最后一行,我收到错误消息" Python对象无法转换为原始类型的指针".我还尝试了其他几种方法,但没有任何效果:

But on the last line I get error "Python objects cannot be cast to pointers of primitive types". I also tried several other approaches, but nothing worked:

# error: 'Foo' is not a type identifier
from foo import Foo
def __init__(self, Foo foo):
    self._impl = new cFooHolder(foo._impl)

# error: 'Foo' is not a type identifier
def __init__(self, foo):
   self._impl = new cFooHolder(<Foo>(foo)._impl)

推荐答案

我找到了解决方案.您必须告诉cython foo._impl实际上是cFoo *实例.这可以通过提供Foo定义来实现(例如,在foo.pxd中).之后,您可以将python对象转换为Foo,而cython会知道其_impl字段的类型为cFoo *.

I found the solution. You have to tell cython that foo._impl is really cFoo* instance. That can be achieved by providing Foo definition (e.g. in foo.pxd). Afterwards you are able to cast python object to Foo and cython will know that its _impl field has type cFoo*.

foo.pxd

from c_foo cimport cFoo
cdef class Foo:
    cdef cFoo* _impl

foo.pyx

from c_foo cimport cFoo
cdef class Foo:
    # methods implementation

c_foo_holder.pxd

cdef extern from "FooHolder.h":
    cdef cppclass cFooHolder:
        cFooHolder(cFoo* foo)

foo_holder.pyx

from c_foo_holder cimport cFooHolder
from c_foo cimport cFoo
from foo cimport Foo

cdef class FooHolder:
    cdef cFooHolder* _impl
    def __init__(self, foo):
        self._impl = new cFooHolder((<Foo?>foo)._impl)

这篇关于将python对象转换为cython指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:03