How to call C++ code in Python (using ctype method)

There are many ways to call C++ code in Python. Here is a more common method, using ctypes .
ctypes is a module in the Python standard library, which can be used to call C functions in the dynamic link library. First, you need to compile the C++ code into a dynamic link library, and then use ctypes to call the compiled dynamic link library.
Taking a simple C++ function as an example, if you want to call this function in Python, you need to do the following steps:
c++ code

using namespace std;

extern "C"{
    
    
  double add(int, int);
}
double add(int x1, int x2)
{
    
    
   double x3 = x1 + x2;
   return x3;
}

Then open the window and enter the following command to convert the above cpp file into an so file. Note that the name of the so file must start with lib.

g++ add.cpp -fpic -shared -o libadd.so

run python code

import ctypes

lib = ctypes.cdll.LoadLibrary("./libadd.so")

int_value1 = 1
int_value2 = 2
# 将函数的返回值类型设置为 double
lib.add.restype = ctypes.c_double
# 将两个整型参数传递给 add 函数
result = lib.add(int_value1, int_value2)
# 输出结果
print(result)  # 3.0

After the above steps, you can successfully use the code written in c++ in Python! However, when the numeric type is involved in the function, you must remember to set the type of the return value, otherwise it will return a wrong result. For example, when the above code cancels lib.add.restype = ctypes.c_double, the result returned will be 1.

Guess you like

Origin blog.csdn.net/change_xzt/article/details/131294860