Visual Studio 2019下使用C++与Python进行混合编程——环境配置与C++调用Python API接口

本文介绍了如何在VS2019环境下使用C++与Python进行混合编程,包括Python库的安装、环境变量配置、PythonCAPI的调用步骤,以及无参和有参函数、类的实例化与调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

  1. 在vs2019下使用C++与Python进行混合编程,在根源上讲,Python 本身就是一个C库,那么这里使用其中最简单的一种方法是把Python的C API来嵌入C++项目中,来实现混合编程。
  2. 当前的环境是,win10,IDE是vs2019,python版本是3.9,python的环境是使用Anacond安装的。

一、环境配置

1. 安装Python
首先要安装好Python的库,Python可以直接从官网下载,或者直接在conda里面进行安装。

2.添加环境变量
安装完成之后,添加两个系统环境变量,分别是:PYTHONHOME和PYTHONPATH。
在这里插入图片描述
如果不添加这两个系统环境变量会报以下的错误:

Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\code\\cpp\\PDFToDoc\\x64\\Release\\PDFToDoc.exe'
  sys.base_prefix = 'C:\\Users\\duole\\anaconda3'
  sys.base_exec_prefix = 'C:\\Users\\duole\\anaconda3'
  sys.platlibdir = 'lib'
  sys.executable = 'C:\\code\\cpp\\PDFToDoc\\x64\\Release\\PDFToDoc.exe'
  sys.prefix = 'C:\\Users\\duole\\anaconda3'
  sys.exec_prefix = 'C:\\Users\\duole\\anaconda3'
  sys.path = [
    'C:\\Users\\duole\\anaconda3\\python39.zip',
    '.\\DLLs',
    '.\\lib',
    'C:\\code\\cpp\\PDFToDoc\\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 0x000042d4 (most recent call first):
<no Python frame>

3. 创建项目
打开vs2019,创建一个空的新C++项目:
在这里插入图片描述
创建完成后打开项目属于配置包含目录与库目录:
在这里插入图片描述
在附加依赖项目里把python的lib库名添加到里面:
在这里插入图片描述
4.添加代码
在项目里面新添一个main.cpp
在这里插入图片描述
main.cpp里面的代码:

#include <Python.h>

int main()
{
   
    Py_Initialize();    // 初始化python解释器
    PyRun_SimpleString("print('hello python')");
    Py_Finalize();      // 释放资源
    return 0;
}

然后运行项目
在这里插入图片描述
这样配置就算法成功了。

二、Python C API 调用

为了方便项目测试,在项目根目录下添加一个script目录,在script目录里面创建一个call_python.py的文件。
在这里插入图片描述

2.1 调用Python代码无参函数

C++调用python无参函数流程:

  1. 初始化python接口(Py_Initialize)
  2. 导入依赖库 (PyRun_SimpleString)
  3. 初始化python系统文件路径(PyRun_SimpleString)
  4. 调用python文件名(PyImport_ImportModule)
  5. 获取函数对象(PyObject_GetAttrString)
  6. 调用函数对象(PyObject_CallObject)
  7. 结束python接口调用,释放资源(Py_Finalize)

在call_python.py里面添加代码:

def test():
    print("hello python to C++")

然后在main.cpp里面进行调用:

int 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值