1、c++ 动态链接库代码,完成动态链接库生成
//实现两个二维数组对应元素相加
// 输入的是一维数组,其实是二维数组每一行首尾相接
// 假设数组为 n行8列,否则需要将列数以参数形式传入
extern "C" __declspec(dllexport) void add_array(double* image_data1, double* image_data2, int rows1, int rows2, double* pair, int* num_key);
#include <iostream>
using namespace std;
void add_array(double* image_data1, double* image_data2, int rows1, int rows2, double* pair, int* num_key)
{
int min_row = min(rows1, rows2);
*num_key = min_row;
for (int i = 0; i < min_row * 8; ++i)
{
pair[i] = image_data1[i] + image_data2[i];
}
}
2、python代码,调用C++动态链接库
# 如何将c++ 源码 封装成C++静态链接库,然后用python调用?
import os
from ctypes import *
import numpy as np
# 加载动态链接库
os.add_dll_directory("G:/123/456/Lib") # 动态链接库所在的绝对路径
test = cdll.LoadLibrary('test01.dll')
# 定义C函数的参数和返回值
test.add_array.argtypes = [
POINTER(c_double),
POINTER(c_double),
c_int,
c_int,
POINTER(c_double),
POINTER(c_int)]
def add_array(array1, array2):
rows1 = len(array1)
rows2 = len(array2)
max_rows = min(rows1, rows2)
# 分配内存用于存储特征点
pair = (c_double * (8 * max_rows))()
result_size = c_int()
# 调用C++函数
test.add_array(array1.ctypes.data_as(POINTER(c_double)),array2.ctypes.data_as(POINTER(c_double)),
rows1, rows2,
pair,
byref(result_size))
# 返回结果的行数
row_result = result_size.value
result = np.zeros((row_result, 8), dtype=np.float64)
for i in range(row_result):
result[i, 0] = pair[8 * i]
result[i, 1] = pair[8 * i + 1]
result[i, 2] = pair[8 * i + 2]
result[i, 3] = pair[8 * i + 3]
result[i, 4] = pair[8 * i + 4]
result[i, 5] = pair[8 * i + 5]
result[i, 6] = pair[8 * i + 6]
result[i, 7] = pair[8 * i + 7]
return result
array1 = np.arange(32).reshape(4, 8).astype(np.float64)
array2 = np.arange(32, 96).reshape(8, 8).astype(np.float64)
#1.传入实数调用demo
result1 = add_array(array1, array2)
print("Array 1:")
print(array1)
print("Array 2:")
print(array2)
print("result")
print(result1)
3、运行结果
