How to wrap a C++ object using pure Python Extension API (python3)?

doom Source

I want to know how to wrap a C++ object with Python Extension API (and distutils) without external tools (like Cython, Boost, SWIG, ...). Just in pure Python way without creating a dll.

Note that my C++ object has memory allocations so destructor has to be called to avoid memory leaks.

#include "Voice.h"

namespace transformation
{ 
  Voice::Voice(int fftSize) { mem=new double[fftSize]; } 

  Voice::~Voice() { delete [] mem; } 

  int Voice::method1() { /*do stuff*/ return (1); } 
}

I just want to do somethings like that in Python :

import voice

v=voice.Voice(512)
result=v.method1()
pythonc++python-3.xwrapping

Answers

answered 5 days ago Maxim Egorushkin #1

You may like to start with Extending Python with C or C++.

You can use standard Python modules source code as examples.

The value provided by Boost.Python, SWIG, etc, is that you do not have to know/understand all the low level details because they handle them for you. This is why people use them.

answered 5 days ago doom #2

Seems that the answer was in fact here : https://docs.python.org/3.6/extending/newtypes.html

With examples, but not really easy.

EDIT :

In fact, it is not really for wrapping a C++ object in a Python object, but rather to create a Python object with C code.

comments powered by Disqus