cmake 静态调用 c++ dll 的类的一个例子(Clion IDE)[更新1:增加1.模版的应用,2.ma 的算法]

时间:2022-12-09 20:31:28

CMakeLists.txt

project(aaa)
add_library(aaa SHARED aaa.cpp)
add_executable(bbb bbb.cpp)
target_link_libraries(bbb aaa)

aaa.h

#pragma once

#ifndef AAA_AAA_H
#define AAA_AAA_H
#endif #ifdef BUILD_AAA_DLL
#define IO_AAA_DLL __declspec(export)
#else
#define IO_AAA_DLL __declspec(import)
#endif IO_AAA_DLL class father
{
private:
const double PI = 3.14;
public:
void hello(void);
/* 该函数用于介绍 dll 的接口
*
*/
double * ma(double *array, int arrayLen, int maLen);
/* 该函数用于计算 ma 值
* array 传入数组
* arrayLen 数组长度
* maLen 计算天数
*/
};

aaa.cpp

#define BUILD_AAA_DLL

#include "aaa.h"
#include <iostream> using namespace std; IO_AAA_DLL void father::hello(void)
{
cout << "+----------------------------------+" << endl;
cout << "|Hello from class.father.hello() |" << endl;
cout << "| --Made by DengChaohai|" << endl;
cout << "+----------------------------------+" << endl; } double * father::ma(double *array, int arrayLen, int maLen)
{
int n = maLen;
// 保存计算天数
double ma[arrayLen];
// 用于保存 ma 值
while(arrayLen >= maLen && maLen >0)
// 传入数组长度要大于计算天数
{
double sum = 0;
for(int i = maLen - n; i < maLen; i++)
// 计算长度不变,但 ma 值计算要一步步移动,
{
sum = sum + array[i];
}
ma[maLen - 1] = sum / n;
// 简单的平均值算法
cout << "wma[" << maLen - 1 << "] = " << ma[maLen - 1] << endl;
maLen++;
}
return ma;
// 返回数组指针,是否调用再说
}

bbb.cpp

#include "aaa.h"
#pragma comment(a, "C:\Users\Perelman\.CLion2016.1\system\cmake\generated\aaa-4d5bae38\4d5bae38\Debug\libaaa.a") #include <iostream>
using namespace std; template <typename t> int getArrayLen(t &array)
// 应用模版,动态定义数据类型
{
return sizeof(array) / sizeof(array[0]);
} int main()
{
father child;
child.hello();
double open[] = {0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23};
double *p = child.ma(open, getArrayLen(open), 1);
cout << *(p + 4);
return 0;
}

cmake 静态调用 c++ dll 的类的一个例子(Clion IDE)[更新1:增加1.模版的应用,2.ma 的算法]

cmake 静态调用 c++ dll 的类的一个例子(Clion IDE)[更新1:增加1.模版的应用,2.ma 的算法]

bbb.py

from ctypes import *
h = windll.LoadLibrary('C:\\Users\\Perelman\\.CLion2016.1\\system\\cmake\\generated\\aaa-4d5bae38\\4d5bae38\\Debug\\libaaa.dll')
h._ZN6father5helloEv()
'''调用函数 hello,此函数名由 depends 工具获得'''
PyList = [0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23]
'''python 的 list 数据'''
CArray = (c_double*len(PyList))(*PyList)
'''转成 c 的 数组格式'''
h._ZN6father2maEPdii(byref(CArray), 13, 3)
'''调用函数 ma,参数 1 的指针用 byref 取'''

cmake 静态调用 c++ dll 的类的一个例子(Clion IDE)[更新1:增加1.模版的应用,2.ma 的算法]

cmake 静态调用 c++ dll 的类的一个例子(Clion IDE)[更新1:增加1.模版的应用,2.ma 的算法]