Python调用C++/C

#include<iostream>
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 <opencv2/opencv.hpp>
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)

相关推荐

  1. Python调用C++/C

    2023-12-31 15:30:03       34 阅读
  2. python调用http接口

    2023-12-31 15:30:03       32 阅读
  3. python 调用dll

    2023-12-31 15:30:03       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-31 15:30:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-31 15:30:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-31 15:30:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-31 15:30:03       20 阅读

热门阅读

  1. SpringBoot入门到精通-Spring Boot Jasypt Encrypt 演示

    2023-12-31 15:30:03       43 阅读
  2. 二叉树-遍历-重写

    2023-12-31 15:30:03       29 阅读
  3. 数据结构-怀化学院期末题(58)

    2023-12-31 15:30:03       38 阅读
  4. 多次运用集成函数处理蛋白质特征数据

    2023-12-31 15:30:03       39 阅读
  5. git教程——日常工作git使用流程

    2023-12-31 15:30:03       42 阅读
  6. Markdown“冷门”语法说明

    2023-12-31 15:30:03       46 阅读
  7. JPA 批量保存超级慢如何解决

    2023-12-31 15:30:03       37 阅读
  8. K8S kubectl 自动补全命令

    2023-12-31 15:30:03       36 阅读
  9. 串口通信技术及其应用

    2023-12-31 15:30:03       40 阅读