一. 准备工作
1)在D:\vs_test\cmake_test目录下,新建t3文件夹;
2)在t3下,新建目录lib、build和文件CMakeLists.txt。lib是用来存放源文件的。
3)在目录lib下,新建CMakeLists.txt和hello.cpp、hello.h。
t3目录下的CMakeLists.txt文件内容:
PROJECT(HELLOLIB)
ADD_SUBDIRECTORY(lib bin)
lib/CMakeList.txt 内容:
SET(LIBHELLO_SRC hello.cpp)
ADD_LIBRARY(hello SHARED ${LIBHELLO_SRC})
lib/hello.cpp 内容:
#include "hello.h"
extern "C" {
__declspec(dllexport) int add(int a, int b);
}
void HelloFunc()
{
std::cout << "Hello World !\n";
while (1);
}
int add(int a, int b)
{
return a+b;
}
extern "C" {
__declspec(dllexport) int add(int a, int b);
}
一定要记得加这一步,不然python访问不到函数。
lib/hello.h 内容:
#ifndef HELLO_H
#define HELLO_H
#include <iostream>
using namespace std;
void HelloFunc();
int add();
#endif
二. 编译共享库
具体的构建方法参考我第一篇文章:【Cmake】在Windows下用Cmake构建C++工程项目——cmake 的 helloworld——1
cmake编译成功之后,可以看到 t3\build\bin\Debug 目录下生成了动态库 hello.dll
注意:如果是在Linux环境下,那么得到的就是 hello.so,这就是我们期望的共享库。
三.Python访问dll
新建一个main.py函数
from ctypes import *
dll = CDLL("hello.dll")
c = dll.add(20,23)
print(c)
代码结构如下
参考
Python调用dll_yangzhichao_csdn的博客-CSDN博客_python 调用dll
把c++的exe工程编译为动态库dll静态库lib,并实现调用(超详细)_耳东广大木木的博客-CSDN博客_exe编译成dll