我正在尝试包装一些使用带有构造函数的结构的 C++ 代码,但不知道如何做。
C++ 结构:
typedef struct point_3d_t
{
double x;
double y;
double z;
point_3d_t(double x, double y, double z)
: x(x)
, y(y)
, z(z)
{}
} point_3d;
Cython 包装器:
cdef extern from "./cppdar.hpp":
ctypedef struct point_3d:
point_3d(double, double, double)
double x;
double y;
double z;
现在,我期望能够通过cdef point_3d p1(v, v, v)之类的东西构造结构(从cython文件中) ,但我似乎无法弄清楚如何让 cython 只使用提供的构造函数。
我试过:
cdef point_3d p1(v, v, v)cdef point_3d p1 = point_3d(v, v, v)cdef point_3d p1(0, 0, 0)cdef point_3d p1 = point_3d(0, 0, 0)
其中 v 是显式 cdef double v = 0,但没有任何作用。
使用简单的 cdef point_3d p1、p1.x = nnnn 等...,但这很烦人,我不明白为什么我不应该这样做我认为能够使用默认构造函数。
试图研究这个问题会产生很多与类构造函数相关的困惑,这没有帮助。
请您参考如下方法:
好的,所以答案是您不能在 cython 中使用构造函数参数堆栈分配 C++ 对象,基本上根本:
发件人:https://groups.google.com/forum/#!topic/cython-users/fuKd-nQLpBs
Yes, it's a limitation, but it's a more fundamental issue than the parser. The construction and destruction of stack-allocated objects in C++ is intricately tied to their scope, and scoping rules are different in Python and C. For example, consider
if some_condition(): x = Foo(1) else: x = Foo(2, 3) return x.method()This simply can't be expressed as such in C++. Conversely
if (some_other_condition()) { Foo_with_RIAA foo(x) } ...wouldn't translate "correctly" Python scoping rules.
Now there are some cases where it could make sense, but significant code generation changes would have to be made, as currently all variables are declared at the top of a function (to follow the C89 standard, which some compilers enforce) but in C++ mode we would have to defer the declaration of the variable to it's instantiation (including avoiding any automatically inserted C-level {} scopes used for simplicity in code generation).
As one can always allocate such complicated objects on the heap, this isn't a significant limitation.
这非常烦人,因为这意味着在许多情况下您不能包装缺少默认构造函数的类。
可怕的、不好的 hacky 解决方法是将构造函数包装在一个简单的 C(++) 函数中,然后通过 cython 公开那个。
