Python调用C++/C

#include
extern "C" {
	int foo(int a, int b) {
		std::cout << "a + b = " << a + b << std::endl;
		return a + b;
	}
}

如果是编译C++代码,需要写上 extern "c"

生成动态文件:g++ -shared -o test.so -fPIC test.cpp (c代码用gcc编译)

如果有opencv,需要链接opencv的库

g++ -shared -o mylib.so -fPIC -I/usr/local/include/opencv4 -L/usr/local/lib test.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui

生成可执行文件

g++ main.cpp -o output_executable -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgcodecs

使用python调用

import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("test.so")
lib.foo(1,3)
print("***********************")
// C++ 代码
#include 
extern "C" uchar* get_random_mat_data() {
    cv::Mat mat = cv::Mat::zeros(10, 10, CV_8UC1);
    cv::randu(mat, cv::Scalar(0), cv::Scalar(255));  // 填充矩阵

    return mat.data;
}
import ctypes
import numpy as np

# 加载 C 动态链接库
lib = ctypes.CDLL('mylib.so')
# 定义函数签名,表示返回值为 uchar* 类型
get_mat_data_func = lib.get_random_mat_data
get_mat_data_func.restype = ctypes.POINTER(ctypes.c_ubyte)
# 调用函数获取数据指针
mat_ptr = get_mat_data_func()
# 使用 NumPy 创建数组
mat = np.ctypeslib.as_array(mat_ptr, shape=(10, 10))
print(mat)

你可能感兴趣的:(C/C++,python,c++)