从C ++调用Cython函数 [英] call Cython function from C++

查看:667
本文介绍了从C ++调用Cython函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++库,它有一个Python包装器(用SWIG编写)。这个库允许执行小的用户定义的代码(回调),例如向量上的元素操作。也就是说而不是只是一个+你可以做任何任意的二进制函数。现在这是通过接受二进制函数的可调用Python对象并调用它来实现的。它的工作原理,但是比在每次迭代时不必反弹到Python的代码慢80倍。

I have a C++ library that has a Python wrapper (written with SWIG). This library allows executing small user-defined code (a callback), such as element-wise operations on a vector. I.e. instead of just a + you can do whatever arbitrary binary function. Right now this is accomplished by accepting a callable Python object for the binary function and calling it. It works, but is about 80 times slower than code that doesn't have to bounce up and down into Python at every iteration.

我如何写/ build / import一个Cython函数可以传递到我的C ++库中,以便可以直接由C ++库调用?

How would I write/build/import a Cython function could be passed into my C++ library so that it can be called directly by the C++ library?

编辑:
如果我只是坚持C,那么我会写如下

If I just stuck to C then I would write something like

EWise(double (*callback)(double, double))

然后EWise将回调(10,20); 等。我想要使​​用任何用户想要的名称来编写 callback ,并且它的指针必须通过Python以某种方式传递给我的C ++库。

EWise would then callback(10, 20); or such. I want callback to be written in Cython, using whatever name the user wants, and a pointer to it has to be passed to my C++ library through Python somehow. That somehow is where I'm unclear.

推荐答案

cython的诀窍在于使用关键字 public

The trick with cython is in using the keyword public

cdef public double cython_function( double value, double value2 ):
    return value + value2

然后命令 cythonize< your_file.pyx> < your_file.c> 将创建您可以包括的标题< your_file.h>
或者,您可以自己创建标题:

Then the command cythonize <your_file.pyx> along with <your_file.c> will create header <your_file.h> that you can include. Alternatively, you can create the header yourself:

#ifdef __cplusplus {
extern "C"
#endif

double cython_function( double value, double value2 );

#ifdef __cplusplus
}
#endif

更新

然后使用Python的一些重叠,您可以使用 ctypes的回调机制

Then with a little overlay from Python you can use ctypes's callback mechanism

func_type = CFUNCTYPE(c_double, c_double, c_double)

your_library.set_callback_function ( func_type(user_modules.cython_function) )

这篇关于从C ++调用Cython函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆