Wrapping C ++ code with python (manually)

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

Note:

  • Both main and header files are written in C ++.
  • Both main and header files, instead of using data structures in the form of arrays, vectors, use the Eigen Library.

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

Can anyone address or give some comments about using python wrpper for such code?

+4
source share
5 answers

Use Boost.Python. Here is my tutorial, earlier in SO Docs.


Using Boost.Python

Everything is very simple when you need to use the C ++ library in a Python project. You can simply use Boost.

First of all, this is a list of the components you need:

  • The CMakeList.txt file because you are going to use CMake.
  • C ++ files of the C ++ project.
  • The python file is your python project.

Let's start with a small C ++ file. Our C ++ project has only one method, which returns some string "This is the first attempt." Name 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
}

Download the CMakeLists.txt file 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

This part of the tutorial is so simple. you can import the library and call method into your python project. Call the MyProject.py python project.

import NativeLib
print (NativeLib.getTryString)

, :

  • build.
  • .
  • cmake -DCMAKE_BUILD_TYPE=Release ..
  • make
  • python MyProject.py. , ++.
+7

:

, , ctypes. , . , (C-), Python script, " " .

+2

:

https://docs.python.org/2/extending/extending.html

, cpp python, , Cython: http://cython.org/

Cython C-, Python , CPP, , Python.

+1

Boost.Python

Python

Boost.Python, Boost.

0

++ CLIF. 2017 , Google . SWIG Python .

It is built on top of Clang for C ++ parsing and requires a relatively idiomatic modern use of the C ++ API (not surprisingly following the Google Style Guide ) than any attempt to let you shoot in the leg with SWIG to "keep things bad."

0
source

Source: https://habr.com/ru/post/1674719/


All Articles