Use C++ code in Python
Python is famous for its simplicity and readability. However, it’s not the fastest language. If you have a performance-critical application, you may want to use C++ code in Python. This post explains how to use C++ code in Python.
If I have Foo
class in C++:
1 |
|
To use it in Python, I need to expose it to C API using extern "C"
:
1 |
|
Then, I need to compile it to a shared library:
1 |
|
Now, I can use it in Python:
1 |
|
Note:
- As I used
new
in C++, I need to delete it in Python to avoid memory leak. That’s why I defined__del__
method. - It’s necessary to define
restype
andargtypes
for each c++ function. Otherwise, Python program may have error or crash.
e.g., If I don’t haverestype
defined forFoo_new
andargtypes
forFoo_delete
, the default return type will beint
. When deletingFoo
object,int
will be passed intoFoo_delete
function. Then we can have error:OSError: exception: access violation reading 0x00000000B7727FAF
This error indicates that I’m trying to delete a block of memory that I don’t have permission to access.