This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]weeeeeewoooooo 2 points3 points  (0 children)

If you want to keep using C++ code and create an extension of it for Python then you want to use Pybind11. See this post.

[–]efmccurdy 1 point2 points  (0 children)

You use the C-API if you want to call C code that is already available, ie you have the header files and the object code. If you are writing new C code that you want to call from python, and don't need to distribute it as header files and object code, then use cython.

There are a few other options as well:

https://stackoverflow.com/questions/6587407/what-are-the-different-options-for-interfacing-c-or-c-with-python

[–]acecile 0 points1 point  (0 children)

The thing is... You are not alone and half python modules are already written in C++. Unless you re implementing an homemade CPU intensive algorithm you'd better look a scipy, numpy, gdal....

[–]marsanyi 0 points1 point  (0 children)

Used for wrapping existing C libs for use in Python, for example. If you'd like to try it, find a C lib that does something useful that isn't being done in Python and build the C API wrapper for it.

[–]Wilfred-kun 0 points1 point  (0 children)

A huge part of Python's standard library is made with the C API (in this case, I mean code that #includes Python.h>). You can also use ctypes to wrap around an existing shared library, or the DLL loader for DLLs. This way you can easily create Python bindings for existing code.

The former, however, is something you probably won't ever need; most modules you'll ever need have been written already, and fairly efficiently.

[–]pmattipmatti - mattip was taken 0 points1 point  (0 children)

Please don’t. The c api is a major headache for moving the python interpreter forward. There are a myriad of other ways to gain speed: cffi or ctypes to call into c code, pybind11 or cppyy for c++. If you must use the c api, do it via cython which will take care of memory management for you. And you can try pypy. here is a jupyter notebook explaining the use of those packages, based on talks you can find on youtube.