步骤
1、编写 C++ 代码并生成共享库
2、在 Python 中使用 ctypes 调用共享库中的函数
1. 编写 C++ 代码并生成共享库
首先,我们编写一个简单的 C++ 代码并生成一个共享库(如 .dll, .so, 或 .dylib)。
C++ 代码 (example.cpp)
// example.cpp
#include <iostream>
extern "C" {
void say_hello() {
std::cout << "Hello from C++!" << std::endl;
}
int add(int a, int b) {
return a + b;
}
struct Point {
int x;
int y;
};
Point create_point(int x, int y) {
Point p;
p.x = x;
p.y = y;
return p;
}
}
编译生成共享库
在 Linux/Mac 上:
g++ -shared -o libexample.so -fPIC example.cpp
在 Windows 上:
g++ -shared -o example.dll example.cpp
2. 在 Python 中使用 ctypes 调用共享库中的函数
Python 代码
import ctypes
import os
# 加载共享库
if os.name == "nt":
example_lib = ctypes.CDLL("./example.dll")
else:
example_lib = ctypes.CDLL("./libexample.so")
# 调用无参数无返回值的函数
example_lib.say_hello()
# 调用有参数和返回值的函数
example_lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
example_lib.add.restype = ctypes.c_int
result = example_lib.add(5, 3)
print(f"5 + 3 = {result}")
# 定义与 C++ 中结构体相同的结构体
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]
# 调用返回结构体的函数
example_lib.create_point.argtypes = (ctypes.c_int, ctypes.c_int)
example_lib.create_point.restype = Point
p = example_lib.create_point(10, 20)
print(f"Point: ({p.x}, {p.y})")
详细解释
1、加载共享库:
使用 ctypes.CDLL 加载共享库。路径可以是相对路径或绝对路径。
2、调用无参数无返回值的函数:
直接调用函数,无需额外设置参数或返回值类型。
3、调用有参数和返回值的函数:
使用 argtypes 指定参数类型列表。
使用 restype 指定返回值类型。
然后调用函数并处理返回值。
4、调用返回结构体的函数:
定义与 C++ 中结构体相同的 Python 结构体。
使用 argtypes 指定函数参数类型。
使用 restype 指定返回结构体类型。
调用函数并处理返回的结构体。