简体   繁体   English

从.cpp文件导入函数到python

[英]importing functions from .cpp file into python

Let me start with a disclaimer that i'm putting this question after lot of research and not finding any direct and step by step example. 让我从免责声明开始,我将这个问题放在大量研究之后,而不是找到任何直接的分步示例。

Have gone through Cython , SWIG, Boostpython documentation but couldn't get a step by step process and so posting here - 已经阅读了Cython,SWIG和Boostpython文档,但无法逐步进行操作,因此请在此处发布-

I have a .cpp & .h file with couple of mathematical functions defined.I want to call them in a python (.py) code file. 我有一个.cpp和.h文件,其中定义了几个数学函数,我想在python(.py)代码文件中调用它们。

How do i integrate?Which is the best and neatest way to go about it. 我如何集成?哪种是最好,最整洁的方式。 Please illustrate 请说明

See this part of the Cython documentation; 请参阅Cython文档的这一部分 it takes you step-by-step through interfacing with a C library. 它需要您逐步完成与C库的接口。

Since i eventually solved it using some of the help provided here and research , let me post the answer. 由于我最终使用这里提供的一些帮助和研究来解决了问题,因此让我发布答案。

I did the import of CPP function via Python using Cython. 我使用Cython通过Python导入了CPP函数。

Cython wraps the Python code with CPP file and compiles the two. Cython用CPP文件包装Python代码并编译两者。 The outcome is a Python module (name of the module can be specified in setup.py file ) and the module can be called as usual. 结果是一个Python模块(可以在setup.py文件中指定该模块的名称),并且可以像往常一样调用该模块。

The issue i was facing was calling a CPP function from Python.So here are my tips for working it out 我面临的问题是从Python调用CPP函数。因此,这是解决该问题的技巧

  1. Define your function in C++ Header and CPP file. 在C ++ Header和CPP文件中定义函数。
  2. Using cdef , define the function in Python script in the beginning where you import modules define other variables.This definition is similar to C++ header file definition 使用cdef在导入模块的开头定义Python脚本中的函数,以定义其他变量,该定义类似于C ++头文件定义
  3. While pasing arguments and arrays to the function call from python , ensure all variables and arrays are type casted as CPP. 在从python向函数调用粘贴参数和数组时,请确保所有变量和数组都类型转换为CPP。
  4. For arrays, it is a bit tricky. 对于数组,这有点棘手。 EG a double array in Python can be type casted using array.array(array_to_cast) . 例如,可以使用array.array(array_to_cast)类型转换类型为Python的double数组。 In the following example, we cast the python array, dev , into the c++ array, dev_arr . 在以下示例中,我们将python数组dev转换为c ++数组dev_arr Note that dev is an array of type double in python, hence the first parameter input to array.array() is 'd' . 请注意, dev是python中double类型的数组,因此输入array.array()的第一个参数是'd'
cdef array.array dev_arr = array.array('d',dev)   

While passing the dev_arr array to your main CPP function, you have to specify this array : data.as_doubles dev_arr数组传递到主要CPP函数时,必须指定以下数组: data.as_doubles

fn_response = cpp_fn_call(stddev_arr.data.as_doubles,...)

Rest will work smoothly. 休息会顺利进行。

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

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