C/C++怎么生成DLL文件?
请参照另外一篇文章:https://blog.csdn.net/Xeon_CC/article/details/122597635
Python代码:
# -*- coding:utf-8 -*-
import ctypes
from ctypes import *
# lib = ctypes.cdll.LoadLibrary('D:\\AllProjects\\py_projects\\radarGP\\QFupdate\\Dll4.dll')
lib = CDLL('D:\\AllProjects\\py_projects\\radarGP\\QFupdate\\Dll4.dll')
"""输入一个一维数组,C语言负责把数组的值乘以20,并返回指针(C语言是无法返回数组对象的,因为C语言没有对象这个概念)"""
list1d = [1, 2, 3, 4, 5]
"""输入一个三维数组,C语言负责把数组的值乘以3,并返回三重指针"""
list3d = [
[[7.3, 2.1, 2.9, 3.7], [4.2, 5.7, 9.1, 4.8]],
[[0.2, 1.2, 4.2, 3.2], [4.2, 5.2, 6.2, 2.8]],
[[0.4, 1.6, 2.4, 0.8], [4.9, 0.7, 6.2, 7.9]],
]
arr_1d = (ctypes.c_int * 5)(*(i for i in list1d))
arr_3d = (c_double * 4 * 2 * 3)(*(tuple(tuple(j) for j in i) for i in list3d))
lib.test_list_func_1d.restype = ctypes.POINTER(c_int)
"""res_list_1d是在C语言返回的 int* 指针类型"""
res_list_1d = lib.test_list_func_1d(byref(arr_1d), len(list1d))
for i in res_list_1d[0:len(list1d)]:
print(i)
print('')
lib.test_list_func_3d.restype = ctypes.POINTER(POINTER(POINTER(c_double)))
"""res_list_3d是在C语言返回的 double*** 三重指针类型"""
res_list_3d = lib.test_list_func_3d(byref(arr_3d))
for i in range(3):
for j in range(2):
for k in range(4):
print res_list_3d[i][j][k],
print('')
print('')
C++代码(以C语言的形式编译):
#define EXPORT __declspec(dllexport)
#include <iostream>
#include <cmath>
#include "list"
using namespace std;
extern "C" {
EXPORT int* test_list_func_1d(int* s_list, int s_list_size) {
for (int i = 0; i < s_list_size; i++) {
*(s_list + i) *= 20;
}
return s_list;
}
EXPORT double*** test_list_func_3d(double s_list[][2][4]) {
//将普通数组转化为指针数组,因为数组是没办法返回的,只能返回指针.
double*** c_list = new double** [3];
for (int i = 0; i < 3; i++) {
*(c_list + i) = new double* [2];
for (int j = 0; j < 2; j++) {
*(*(c_list + i) + j) = new double[4];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 4; k++) {
*(*(*(c_list + i) + j) + k) = s_list[i][j][k] * 3;
}
}
}
return c_list;
}
}
将C++源代码生成DLL文件:
在这里,我们用的是Python2.7,所以以Debug模式的x86导出DLL文件(不要忘了设置预编译头为”不适用预编译头“)
查看一下运行结果: