例子
- C++端代码:
#include
#include <opencv2/opencv.hpp>
// 声明函数
//必须加 extern “C” __declspec(dllexport) ,保证函数是导出的且以C语言的函数名来变形,保证python端可以正确调用到
extern “C” __declspec(dllexport) void processImage(const char* imagePath);
void processImage(const char* imagePath)
{
printf(“imagePath = %s\n”, imagePath);
cv::Mat image = cv::imread(imagePath);
if (image.empty())
{
std::cout << “Failed to open image” << std::endl;
return;
}
printf(“begin 11\n”);
cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);
cv::GaussianBlur(image, image, cv::Size(5, 5), 0);
cv::Canny(image, image, 50, 150);
printf("begin 22\n");
cv::imshow("Processed Image", image);
cv::waitKey(0);
}
需将C++代码编译成动态库(.so或*.dll),以上例子调用到了opencv库,工程中需配置opencv库才能正确编译*
vs编译的dll库,可以基于vs自带的dumpbin工具来查看是否有将c++封装的接口函数正确的导出
- python端代码:
import ctypes #基于ctypes来调用c++端接口
image_path = “F:/Project/demo/example/demo.jpg”
lib = ctypes.CDLL(“./process.dll”) # 替换为您生成的实际共享库文件名
lib.processImage(image_path.encode(‘utf-8’)) #需将编码转换为’utf-8’格式