Simple Python Calling C++ Program

Click on the aboveBeginner Learning Vision” to select “Star” or “Pin

Important content delivered at the first time

Methods for Python Calling C/C++ Programs

Recently, while debugging, I encountered a situation where Python was running very slowly. Therefore, I researched methods to embed C++ programs in Python and recorded them for future reference.

Generally, calling C/C++ programs in Python can be divided into 3 steps:

  • 1. Write the C/C++ implementation program. – 2. Compile the C/C++ program into a dynamic library. – 3. Call the compiled library in Python. There are some differences to note when Python calls C/C++ programs.

1. Python Calling C Functions

Calling C language programs from Python is relatively simple. Compile the C program and then use the ctypes module in Python to call it.

C Language Source File: called_c.c

// Compilation command gcc -o libpycall.so -shared -fPIC called_c.c
#include<stdio.h>
int foo(int a, int b){<!-- -->
printf("a:%d, b:%d.", &a, &b);
return 0;
}

Input the following in the command line or terminal:

gcc -o libpycall.so -shared -fPIC called_c.c

This generates the libpycall.so dynamic library file, which can then be used to call the foo function in Python. Python File: py_call_c.py

import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycall.so') // Path of the library file just generated
lib.foo(1, 3)

Running py_call_c.py outputs:

a:1, b:3

2. Python Calling C++ Classes

Since C++ supports function overloading, when compiled with g++ in C++ mode, the compiler adds additional information to the function names, making it impossible for the ctypes module to find the functions generated by g++. Therefore, to allow g++ to compile in C language mode so that it can find the generated function names, the extern keyword must be used to wrap the code.

C++ Source File: cpp_called.cpp

// Python calling c++ (class) dynamic link library
#include <iostream>
using namespace std;
 
class TestLib
{<!-- -->
    public:
        void display();
        void display(int a);
};
void TestLib::display() {<!-- -->
    cout<<"First display"<<endl;
}
 
void TestLib::display(int a) {<!-- -->
    cout<<"Second display:"<<a<<endl;
}
extern "C" {<!-- -->
    TestLib obj;
    void display() {<!-- -->
        obj.display();
      }
    void display_int(int a) {<!-- -->
        obj.display(a);
      }
}

Input the compilation command in the command line or terminal:

g++ -o libpycallcpp.so -shared -fPIC cpp_called.cpp

Explanation of compilation parameters: -fPIC: Generates position-independent code suitable for dynamic linking; -L path: Indicates to search for library files in the path directory, such as -L. means in the current directory; -I path: Indicates to search for header files in the path directory; -o file: Specifies the output file as file; -shared: Generates a shared library file;

Generate libpycallcpp.so and call it in Python. Python File: py_call_c.py

import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycallcpp.so') // Path of the library file just generated
lib.display()
lib.display_int(0)

Output:

First display
Second display:0

OK, basic functionality achieved, advanced calls will be filled in later


Download 1: OpenCV-Contrib Extension Module Chinese Version Tutorial

Reply "Chinese Tutorial for Extension Modules" in the "Beginner Learning Vision" public account to download the first Chinese version of the OpenCV extension module tutorial, covering installation of extension modules, SFM algorithms, stereo vision, target tracking, biological vision, super-resolution processing, and more than twenty chapters of content.

Download 2: Python Vision Practical Project 52 Lectures

Reply "Python Vision Practical Projects" in the "Beginner Learning Vision" public account to download 31 vision practical projects including image segmentation, mask detection, lane line detection, vehicle counting, eyeliner addition, license plate recognition, character recognition, emotion detection, text content extraction, face recognition, etc., to help quickly learn computer vision.

Download 3: OpenCV Practical Project 20 Lectures

Reply "OpenCV Practical Project 20 Lectures" in the "Beginner Learning Vision" public account to download 20 practical projects based on OpenCV, facilitating advanced learning of OpenCV.

Discussion Group

Welcome to join the public account reader group to communicate with peers. Currently, there are WeChat groups for SLAM, 3D vision, sensors, autonomous driving, computational photography, detection, segmentation, recognition, medical imaging, GAN, algorithm competitions, etc. (will gradually be subdivided in the future). Please scan the WeChat ID below to join the group, and note: "Nickname + School/Company + Research Direction", for example: "Zhang San + Shanghai Jiao Tong University + Vision SLAM". Please follow the format for remarks, otherwise, you will not be allowed in. After successfully adding, you will be invited to relevant WeChat groups based on your research direction. Please do not send advertisements in the group, otherwise, you will be removed from the group. Thank you for your understanding~

Leave a Comment