0%

C++调用python库-Pybind11

自动摘要: 1.下载python3.8安装包 运行python3.8.5amd64.exe,并将各种选项取消,pip选项除外,用于安装第三方库 2.安装相关库 ```pyt ……..

1. 下载python3.8安装包

运行python-3.8.5-amd64.exe,并将各种选项取消,pip选项除外,用于安装第三方库

2. 安装相关库

1
.\python.exe -m pip install trimesh pybind11

3. 将python包移动到exe运行目录下

  • 建议命名为PythonEnv以作区分

4. cmake配置

1
2
3
4
5
6
7
8
9
10
cmake_minimum_required(VERSION 3.21)
project(test)

set(CMAKE_CXX_STANDARD 14)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)#设置可执行文件的输出目录
set(pybind11_DIR F:\\My_Project\\pybind11_test\\include)#设置pybind11路径
find_package (pybind11 REQUIRED)

add_executable(test main.cpp trimesh.h )
target_link_libraries(test PRIVATE pybind11::embed)#链接pybind11依赖

5. main函数注意事项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdlib>
#include <direct.h>
#pragma comment(lib, "F:\\My_Project\\pybind11_test\\lib\\Debug\\trimeshlib.lib")

int main()
{
//获取exe运行绝对路径
const int MAXPATH = 250;
char tmp[MAXPATH];
getcwd(tmp, MAXPATH);
std::string exe_path = tmp;
std::cout << "The current directory is"<< exe_path<<std::endl;

std::string python_home= "PYTHONHOME="+exe_path +"\\PythonEnv";
std::string python_path= "PYTHONPATH="+exe_path +"\\PythonEnv";

//设置系统环境变量,pybind11是头文件,所以需要告诉PYTHONHOME,PYTHONPAHT的路径
putenv(python_home.c_str());
putenv(python_path.c_str());

}

6. 复制python3.8.dll到exe运行目录下

MSVC编译器不会自动把python38.dll 放入exe运行目录下

7. 未来计划

  1. 自动找出运行所有依赖并复制到exe目录下,最大能力精简pythonEnv环境
  2. 对python第三库进行zip压缩化(利用python嵌入式包_pth方法)
  3. 对python源码进行二进制化或者加密

欢迎关注我的其它发布渠道