C++ 混合Python编程 及 Visual Studio配置

文章目录

需求

接手了一个C++应用程序,解析csv和生成csv文件,但是如果要把多个csv文件合并成一个Excel,分布在不同的Sheet中,又想在一次运行中完成,不想说运行完C++ 的App后,再调用一个Python脚本或程序,这需要两步操作

配置环节

明确安装的是64位

根据安装的Visual Studio 的版本,我安装的是64-bit的。 如何查看当前Python已安装的python位数或者版本

在cmd模式下输入python,可以看到已安装64bit版本,

shell 复制代码
C:\Users\xxx>python
Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr  5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
shell 复制代码
C:\Users\xxx>where python
C:\Program Files\Python310\python.exe
C:\Users\xxx\AppData\Local\Microsoft\WindowsApps\python.exe

Python安装目录

- python.h 所在目录: C:\Program Files\Python310\include

  • python libraries 目录: C:\Program Files\Python310\libs

当设置Visual Studio工程属性时,需要用到上述目录

创建Console C++ Project

创建一个工程,然后配置工程属性

Cpp 调用 Python Demo

参考代码

cpp 复制代码
#include <Windows.h>
#include <iostream>
#include <string>
#include <Python.h>


using namespace std;

// https://docs.python.org/3/extending/embedding.html
void CallPython(string PythonModuleName, string PythonFunctionName)
{
	char* funcname = new char[PythonFunctionName.length() + 1];
	strcpy_s(funcname, PythonFunctionName.length() + 1, PythonFunctionName.c_str());

	char* modname = new char[PythonModuleName.length() + 1];
	strcpy_s(modname, PythonModuleName.length() + 1, PythonModuleName.c_str());

	printf("Hit any key to initialize the Python interpreter\n");
	system("pause");

	// Initialize the Python interpreter 
	// https://docs.python.org/3/c-api/init.html#c.Py_Initialize
	Py_Initialize();

	TCHAR cwd[2048];
	GetCurrentDirectory(sizeof(cwd), cwd);

	// Import a module. This is best described by referring to the built-in Python function __import__().
	// https://docs.python.org/3/c-api/import.html?highlight=pyimport_importmodule#c.PyImport_ImportModule 
	printf("Hit any key to Load the Python module %ws - %s\n", cwd, modname);
	system("pause");
	PyObject* my_module = PyImport_ImportModule(modname);

	// Print a standard traceback to sys.stderr and clear the error indicator
	// https://docs.python.org/3/c-api/exceptions.html?highlight=pyerr_print#c.PyErr_Print
	PyErr_Print();

	printf("Module found\n");
	printf("Hit any key to find function %s from Python module %ws\n", funcname, cwd);
	system("pause");

	// Get the address of the particular Python function in the imported module
	// https://docs.python.org/3/c-api/object.html?highlight=pyobject_getattrstring#c.PyObject_GetAttrString
	printf("Getting address of %s in Python module\n", funcname);
	PyObject* my_function = PyObject_GetAttrString(my_module, funcname);

	PyErr_Print();

	printf("Function found\n");
	printf("Hit any key to call function %s from Python module %ws\n", funcname, cwd);
	system("pause");

	// Call a callable Python object callable, with arguments given by the tuple args. 
	// If no arguments are needed, then args can be NULL.
	// https://docs.python.org/3/c-api/call.html?highlight=pyobject_callobject#c.PyObject_CallObject
	PyObject* my_result = PyObject_CallObject(my_function, NULL);

	PyErr_Print();

	printf("Your function has been called\n");
	system("pause");

	// Undo all initializations made by Py_Initialize() and subsequent use of Python/C API functions, 
	// and destroy all sub-interpreters (see Py_NewInterpreter() below) that were created and not yet 
	// destroyed since the last call to Py_Initialize(). Ideally, this frees all memory allocated by the Python interpreter.
	// https://docs.python.org/3/c-api/init.html?highlight=py_finalize#c.Py_FinalizeEx
	Py_Finalize();

	delete[] funcname;
	delete[] modname;
}

int main()
{
	CallPython("PythonFile", "helloworld");
	system("pause");
	return 0;
}

上述代码编译通过后,如果直接运行,会Failed, 原因是我们并没有定义PythonFile module.在Debug模式下,生成的exe文件在x64目录下:

python 复制代码
import re
import string

def helloworld():
	print("Hello from Python!")

main函数内,

  • PythonFile 对应了 PythonModuleName
  • helloworld 对应了 PythonFunctionName

运行Demo后的输出结果

shell 复制代码
Hit any key to initialize the Python interpreter
请按任意键继续. . .
Hit any key to Load the Python module C:\Resource\App\Python\CppPython\CppPython - PythonFile
请按任意键继续. . .
Module found
Hit any key to find function helloworld from Python module C:\Resource\App\Python\CppPython\CppPython
请按任意键继续. . .
Getting address of helloworld in Python module
Function found
Hit any key to call function helloworld from Python module C:\Resource\App\Python\CppPython\CppPython
请按任意键继续. . .
Hello from Python!
Your function has been called
请按任意键继续. . .
请按任意键继续. . .

参考

C++与Python混合编程

相关推荐
hummhumm21 分钟前
第 25 章 - Golang 项目结构
java·开发语言·前端·后端·python·elasticsearch·golang
杜小满25 分钟前
周志华深度森林deep forest(deep-forest)最新可安装教程,仅需在pycharm中完成,超简单安装教程
python·随机森林·pycharm·集成学习
hunandede28 分钟前
av_image_get_buffer_size 和 av_image_fill_arrays
c++
databook1 小时前
『玩转Streamlit』--布局与容器组件
python·机器学习·数据分析
怀澈1222 小时前
高性能服务器模型之Reactor(单线程版本)
linux·服务器·网络·c++
nuclear20112 小时前
使用Python 在Excel中创建和取消数据分组 - 详解
python·excel数据分组·创建excel分组·excel分类汇总·excel嵌套分组·excel大纲级别·取消excel分组
chnming19872 小时前
STL关联式容器之set
开发语言·c++
Lucky小小吴2 小时前
有关django、python版本、sqlite3版本冲突问题
python·django·sqlite
威桑2 小时前
MinGW 与 MSVC 的区别与联系及相关特性分析
c++·mingw·msvc
熬夜学编程的小王3 小时前
【C++篇】深度解析 C++ List 容器:底层设计与实现揭秘
开发语言·数据结构·c++·stl·list