在VS+Cmake+C++中正确链接Conda环境Python解释器的问题
C++调用Conda环境中Python库的运行问题
环境与配置情况
- 系统:Windows
- 开发工具:Visual Studio 2022、CMake 3.20+
- Python环境:Anaconda虚拟环境(Python3.10),已安装NumPy、matplotlib等库
- VS启动方式:先激活目标Conda环境,再执行
start devenv启动VS,确保VS识别该环境
CMakeLists.txt配置如下:
cmake_minimum_required (VERSION 3.20) project(MyProject) add_executable (${CMAKE_PROJECT_NAME} "MyProject.cpp" "MyProject.h") find_package(Python3 REQUIRED COMPONENTS Development Interpreter NumPy REQUIRED) include_directories(${Python3_INCLUDE_DIRS} ${Python3_NumPy_INCLUDE_DIRS} ) target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Python3::Python) include(CMakePrintHelpers) cmake_print_variables(Python3_EXECUTABLE) cmake_print_variables(Python3_INCLUDE_DIRS)
CMake输出已确认获取到正确的Conda环境:
1> [CMake] -- Python3_EXECUTABLE="C:/Users/user/anaconda3/envs/myenv/python.exe" 1> [CMake] -- Python3_INCLUDE_DIRS="C:/Users/user/anaconda3/envs/myenv/include"
运行错误情况
程序编译通过,但调用Python函数时启动失败,报错如下:
Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'plotting' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Users\\user\\source\\repos\\MyProject\\out\\build\\x64-release\\MyProject.exe' sys.base_prefix = 'C:\\Users\\user\\anaconda3\\envs\\myenv' sys.base_exec_prefix = 'C:\\Users\\user\\anaconda3\\envs\\myenv' sys.platlibdir = 'lib' sys.executable = 'C:\\Users\\user\\source\\repos\\MyProject\\out\\build\\x64-release\\MyProject.exe' sys.prefix = 'C:\\Users\\user\\anaconda3\\envs\\myenv' sys.exec_prefix = 'C:\\Users\\user\\anaconda3\\envs\\myenv' sys.path = [ 'C:\\Users\\user\\anaconda3\\envs\\myenv\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Users\\user\\source\\repos\\MyProject\\out\\build\\x64-release', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00001ef8 (most recent call first): <no Python frame>
查询得知该错误与PYTHONPATH、PYTHONHOME未正确配置有关,尝试手动设置变量:
(myenv) set PYTHONPATH=C:\Users\user\anaconda3\envs\myenv (myenv) set PYTHONHOME=C:\Users\user\anaconda3\envs\myenv\Lib\site-packages
修改后错误变化,但仍无法正常运行,报错:
Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html
注:已确认在该Conda环境中直接启动Python可正常加载NumPy。
需求
如何让C++代码正确链接并调用对应Conda Python环境中的库?
内容的提问来源于stack exchange,提问作者ScottP
相关产品推荐
相关产品推荐

