如何在 Cython 中定义返回 cpp 定义类型的函数?
How to define a function returning a cpp-defined type in Cython?
问题概述
我会尽可能简短。
假设我有一个 class Bar
,在 ./cpp/Bar.h
中定义并在 ./cpp/Bar.cpp
中实现。
然后,我有另一个 class、Foo
,在 ./cpp/Foo.h
中定义并在 ./cpp/Foo.cpp
中实现。
Foo
中的方法之一returns指向Bar
的指针,即:
Bar* fubar()
{
Bar* value;
/*irrelevant computation*/
return value;
}
Following the cython docs,我把这两个class移植到了下面
./Foo.pxd
cdef extern from "./cpp/Foo.cpp" namespace "Baz":
pass
cdef extern from "./cpp/Foo.h" namespace "Baz":
cdef cppclass Foo:
Foo() except +
Bar fubar() ## ERROR: Bar is not a type identifier
./PyFoo.pyx
from Foo cimport Foo
from PyBar import PyBar
cdef class PyFoo:
cdef Foo c_foo
def __cinit__(self):
self.c_foo = Foo()
def fubar(self) -> PyBar:
return self.c_foo.fubar()
./Bar.pxd
cdef extern from "./cpp/Bar.cpp" namespace "Baz":
pass
cdef extern from "./cpp/Bar.h" namespace "Baz":
cdef cppclass Bar:
Bar() except +
./PyBar.pyx
from Bar cimport Bar
cdef class PyBar:
cdef Bar c_bar
def __cinit__(self):
self.c_bar = Bar()
在编译过程中,当它到达 ./PyFoo.pyx
时,我收到通知“Bar 不是类型标识符”。
期望的行为
成功编译 Cython 模块,PyFoo.fubar()
返回 PyBar
的实例。
我尝试了什么
- 我在网上找到的关于添加 Cpp 类型的唯一帮助是模板 classes
- 将这些行添加到
./Foo.pxd
cdef extern from "./cpp/Bar.h" namespace "Baz":
pass
将所需的头文件公开到此文件没有帮助
我认为您的问题不是 C++ headers,而是知道类型存在的 Cython。您可以通过 cimport
ing pxd 文件来做到这一点。
Foo.pxd 变为:
cimport Bar
cdef extern from "./cpp/Foo.h" namespace "Baz":
cdef cppclass Foo:
Foo() except +
Bar.Bar fubar()
请注意,我还删除了 C++ 文件的文本包含。也从 Bar.pxd 中删除它。我建议改为将其添加到 "sources" list in your setup.py file。
问题概述
我会尽可能简短。
假设我有一个 class Bar
,在 ./cpp/Bar.h
中定义并在 ./cpp/Bar.cpp
中实现。
然后,我有另一个 class、Foo
,在 ./cpp/Foo.h
中定义并在 ./cpp/Foo.cpp
中实现。
Foo
中的方法之一returns指向Bar
的指针,即:
Bar* fubar()
{
Bar* value;
/*irrelevant computation*/
return value;
}
Following the cython docs,我把这两个class移植到了下面
./Foo.pxd
cdef extern from "./cpp/Foo.cpp" namespace "Baz":
pass
cdef extern from "./cpp/Foo.h" namespace "Baz":
cdef cppclass Foo:
Foo() except +
Bar fubar() ## ERROR: Bar is not a type identifier
./PyFoo.pyx
from Foo cimport Foo
from PyBar import PyBar
cdef class PyFoo:
cdef Foo c_foo
def __cinit__(self):
self.c_foo = Foo()
def fubar(self) -> PyBar:
return self.c_foo.fubar()
./Bar.pxd
cdef extern from "./cpp/Bar.cpp" namespace "Baz":
pass
cdef extern from "./cpp/Bar.h" namespace "Baz":
cdef cppclass Bar:
Bar() except +
./PyBar.pyx
from Bar cimport Bar
cdef class PyBar:
cdef Bar c_bar
def __cinit__(self):
self.c_bar = Bar()
在编译过程中,当它到达 ./PyFoo.pyx
时,我收到通知“Bar 不是类型标识符”。
期望的行为
成功编译 Cython 模块,PyFoo.fubar()
返回 PyBar
的实例。
我尝试了什么
- 我在网上找到的关于添加 Cpp 类型的唯一帮助是模板 classes
- 将这些行添加到
./Foo.pxd
将所需的头文件公开到此文件没有帮助cdef extern from "./cpp/Bar.h" namespace "Baz": pass
我认为您的问题不是 C++ headers,而是知道类型存在的 Cython。您可以通过 cimport
ing pxd 文件来做到这一点。
Foo.pxd 变为:
cimport Bar
cdef extern from "./cpp/Foo.h" namespace "Baz":
cdef cppclass Foo:
Foo() except +
Bar.Bar fubar()
请注意,我还删除了 C++ 文件的文本包含。也从 Bar.pxd 中删除它。我建议改为将其添加到 "sources" list in your setup.py file。