使用python调用C/C++动态链接库

有时要进行算法部署的加速,要把一些算法模块写成C/C++,如何混合编程,用python去调用C/C++呢?

首先把算法用C/C++写好,然后打包算法的动态链接库,具体方法参考:如何打包动态链接库

需要注意:如果是C++,在代码前后加上extern "C" {C++代码函数}。 //需要调用的C++程序就把声明写到这个extern "C"范围中

如果是ubuntu下,生成动态链接库so

之后开始python封装C/C++。

话不多说,上例子:

import ctypes
import cv2
import numpy as np
import time
from ctypes import *

## int ImgCheck(int height, int width, uchar* img_data);
## input: 图像高 图像宽 图像信息
## output: int类型
def Check_C(img_data):
    ll = ctypes.cdll.LoadLibrary
    lib = ll("./libImgCheck.so")
    lib.ImageCheck.restype = ctypes.c_int
    frame_data = img_data.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte))
    R = lib.ImgCheck(img_data.shape[0], img_data.shape[1], frame_data)

    return R

if __name__ == '__main__':
    frame = cv2.imread('time.jpg')

    start_time = time.time()

    Result = Check_C(frame)
    print("Result: ", Result)

    elapse_time = time.time() - start_time
    print("cost time (s):", elapse_time)

对于多张图片路径输入,可以这样python封装:

import ctypes
import cv2
import numpy as np
import time
from ctypes import *


## int ImgCompare(char* img_1, char* img_2)
## ./Test 1.jpg 2.jpg

def image_compare(image_path_1, image_path_2):
    image_paths = [image_path_1, image_path_2]
    ll = ctypes.cdll.LoadLibrary
    lib = ll("./libImgCompare.so")
    lib_ImageCompare = lib.ImgCompare
    lib_ImageCompare.argtypes = [c_char_p() , c_char_p()]
    lib_ImageCompare.restype = c_int
    r_flag = lib_ImageCompare(image_paths[0].encode('utf-8'), image_paths[1].encode('utf-8'))

    return r_flag

if __name__ == '__main__':
    img_path_1 = '1.jpg'
    img_path_2 = '2.jpg'

    start_time = time.time()

    Result = image_compare(img_path_1, img_path_2)
    print("Result: ", Result)

    elapse_time = time.time() - start_time
    print("cost time (s):", elapse_time)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值