2

I am new to object oriented programming and I am struggling to find a good tutorial on how to make a library in C++ that I can import into Python.

At the moment I am just trying to make a simple example that adds two numbers. I am confused about the process. Essentially I want to be able to do something like this in Python:

import MyCPPcode

MyCPPcode.Add(5,3) #function prints 5+3=8

I am not requesting a full example with code, just the steps that I need to take. Do I need to make a .dll or a static library? I am using MS Visual Studio 2013.

Also, does the process tailor the C++ library code for Python in any way or will this library be available for other languages as well?

turnip
  • 2,246
  • 5
  • 30
  • 58
  • How about the [Boost Python](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/) library? It wouldn't have been hard ti find yourself with a little bit of searching. – Some programmer dude Jul 16 '14 at 10:41
  • @JoachimPileborg From what I have already researched/tried using Boost for a simple example like this will complicate things more than if I just use `ctypes`. – turnip Jul 16 '14 at 10:44
  • Have you checked the examples in the [tutorial](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/index.html)? Much more simpler than that is going to be hard to beat. – Some programmer dude Jul 16 '14 at 10:47
  • http://stackoverflow.com/questions/5081875/ctypes-beginner It's dead simple. – notorious.no Jul 16 '14 at 10:52
  • 1
    Probably you won't stick to code as trivial as this. Boost of course has a larger overhead, but using `ctypes` will become hard if you're c++ library gets classes and more functions... – sebastian Jul 16 '14 at 10:53
  • @sebastian I think I will consider using Boost because after all my intentions are to create a more complex library. – turnip Jul 16 '14 at 10:57

1 Answers1

3

While I cannot guide you through the whole process, because I do not know python too well, Here is what I know:

It is absolutely possible. While not being something for someone who is new to object-oriented programing, it's called the python-C/C++ API. If you search for that in the python documentation there are several chapters about it.

While the example function you're showing might look like that from python, the process is a lot more redundant in c++ (behind the scenes). There are tools that combat that issue, for example Cython, but if you want to learn I'd suggest going pure python API.

As for availability with other languages... Well, the internal functions (i.e. adding two numbers) are of course general c++, so you can reuse them in other projects, but yes, the created library will be made to work with python, and not something else.

Ludwik
  • 2,247
  • 2
  • 27
  • 45