简体   繁体   English

如何将返回C ++自定义类的函数与Cython接口?

[英]How to interface a function that returns a C++ custom class with Cython?

I have this C++ function prototype: 我有这个C ++函数原型:

 Bar & getBar()

where Bar is a user-defined C++ class. 其中Bar是用户定义的C ++类。 Now I would like to interface this function with Cython, in the simpliest way possible. 现在,我想以最简单的方式将此功能与Cython接口。

My .pyx file looks like this: 我的.pyx文件如下所示:

cdef class PyBar:
   cdef Bar* thisptr 
   (...)

def pygetBar():
   cdef Bar bar = getBar()  
   cdef PyBar pybar = PyBar()

   (*pybar.thisptr) =  bar  # <-- too bad, do not work

Whatever I try I cannot copy a C++ Bar instance in a 'thisptr'. 无论我如何尝试,都无法在“ thisptr”中复制C ++ Bar实例。 For the line above, I get this Cython error message: 对于上面的行,我收到此Cython错误消息:

 Cannot assign type 'Bar' to 'Bar *'

The only solution I found is to define a C++ helper function that just does the copy: 我发现的唯一解决方案是定义一个仅执行复制的C ++辅助函数:

void helper_copy_bar(Bar* source, Bar* destination)
{ *destination = *source }

While this works, it's pretty annoying to create a new C++ function each time I just want to interface such a simple function. 尽管这可行,但是每次我只想接口这样一个简单的函数时,创建一个新的C ++函数就很烦人了。 There must be something I'm missing from the docs. 文档中肯定缺少某些内容。

Edit : 编辑

I found a workaround which has other disadvantages: 我发现一种解决方法还有其他缺点:

 def pygetBar():
    cdef Bar * bar = new Bar(getBar())  
    cdef PyBar pybar = PyBar()
    del pybar.thisptr
    pybar.thisptr = bar

    return pybar

It still involves a useless new/delete of a c++ object but at least there is no need for an external function (good for the lazy). 它仍然涉及c ++对象的无用的new / delete,但至少不需要外部函数(对惰性函数有利)。 I'm still wondering which solution (an external function or the second one) is better, and if there is a way to use the first solution without an external function. 我仍然想知道哪种解决方案(外部函数或第二种)更好,以及是否有一种方法可以在没有外部函数的情况下使用第一种解决方案。

Bar& is reference to Bar, it is not a pointer to Bar, although internally, compilers may implement it as a pointer. Bar&是对Bar的引用 ,它不是Bar的指针,尽管在内部,编译器可以将其实现为指针。 Easiest way to simplify this would be to write a helper C function, I'm not aware that Cython has explicit support for C++? 简化此过程的最简单方法是编写一个辅助C函数,我不知道Cython对C ++有明确的支持吗? Your "workaround" looks suitable. 您的“解决方法”看起来很合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM