用python包装C ++代码(手动) [英] Wrapping C++ code with python (manually)

查看:51
本文介绍了用python包装C ++代码(手动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主文件(main.cpp)和一个头文件(nodes.hpp).主文件采用N(任何正整数)作为输入参数,并通过使用头文件的功能给出输出"x&y'(均为double).

I have a main file(main.cpp) and a header file(nodes.hpp). The main file takes N(any positive integer) as input argument and by using the functions of header file it gives output say 'x & y' (both double).

注意:

  1. 主文件和头文件都是用C ++编写的.
  2. 主文件和头文件都不要使用数据结构作为数组,向量,而要使用特征库.

我必须为他们编写一个python包装器,我具有python的使用知识,但从未使用过任何包装器.

I have to write a python wrapper for them, I have working knowledge of python but have never used any wrapper.

有人可以参考或提供有关使用python wrpper进行此类代码的注释吗?

Can anybody please refer or give some notes about using python wrpper for such code?

推荐答案

使用Boost.Python.这是我的教程,以前是关于SO Docs的.

Use Boost.Python. Here is my tutorial, previously on SO Docs.

使用Boost.Python

当您必须在Python项目中使用C ++库时,事情很容易.只是您可以使用Boost.

Things are easy when you have to use a C++ library in a Python project. Just you can use Boost.

首先,这里是您需要的组件列表:

First of all here is a list of components you need:

  • 一个CMakeList.txt文件,因为您将要使用CMake.
  • C ++项目的C ++文件.
  • python文件-这是您的python项目.

让我们从一个小的C ++文件开始.我们的C ++项目只有一个方法,该方法返回一些字符串这是第一次尝试".称为 CppProject.cpp

Let's start with a small C++ file. Our C++ project has only one method which returns some string "This is the first try". Call it CppProject.cpp

char const *firstMethod() {
    return "This is the first try.";
}

BOOST_PYTHON_MODULE(CppProject) {
    boost::python::def("getTryString", firstMethod); // boost::python is the namespace
}

在下面有一个CMakeLists.txt文件:

Have a CMakeLists.txt file a below:

cmake_minimum_required(VERSION 2.8.3)
FIND_PACKAGE(PythonInterp)
FIND_PACKAGE(PythonLibs)
FIND_PACKAGE(Boost COMPONENTS python)

INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})

PYTHON_ADD_MODULE(NativeLib CppProject)
FILE(COPY MyProject.py DESTINATION .) # See the whole tutorial to understand this line

通过本教程的这一部分,一切都变得如此简单.您可以在python项目中导入库和调用方法.调用您的python项目 MyProject.py .

By this part of the tutorial everything is so easy. you can import the library and call method in your python project. Call your python project MyProject.py.

import NativeLib
print (NativeLib.getTryString)


要运行您的项目,请遵循以下说明:


In order to run your project follow the instructions below:

  • 创建一个名为 build 的目录.
  • 进入该目录.
  • 给出命令 cmake -DCMAKE_BUILD_TYPE =发布..
  • make
  • python MyProject.py .现在,您必须查看C ++项目中的方法返回的字符串.
  • Create a directory with the name build.
  • Enter into that directory.
  • Give the command cmake -DCMAKE_BUILD_TYPE=Release ..
  • make
  • python MyProject.py. Now, you have to see the string which the method in your C++ project returns.

这篇关于用python包装C ++代码(手动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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