解决C++调用Python中文乱码问题

Chloe
Chloe
发布时间:2026-10-11| 3人浏览过
原创

本文详细解析了C++调用Python时出现中文乱码的原因,并提供完整的解决方案。通过设置执行字符集和实现GBK到UTF-8的转换函数,确保中文字符在跨语言调用中正确传递。

问题背景

在Windows环境下,Visual Studio C++项目默认使用GB2312编码,而Python默认使用UTF-8编码。当C++程序调用Python脚本并传递包含中文字符的字符串时,由于编码不一致,会导致中文显示为乱码。

解决方案

1. 设置执行字符集

在C++程序顶部添加以下预处理指令,指定执行字符集为GB2312:

#pragma execution_character_set("GB2312")

2. 实现编码转换函数

为了实现从GBK到UTF-8的转换,可以使用Windows API函数MultiByteToWideChar和WideCharToMultiByte。以下是完整的转换函数代码:

string GbkToUtf8(const char* src_str)
{
  int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0);
  wchar_t* wstr = new wchar_t[len + 1];
  memset(wstr, 0, len + 1);
  MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len);
  len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
  char* str = new char[len + 1];
  memset(str, 0, len + 1);
  WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
  string strTemp = str;
  if (wstr) delete[] wstr;
  if (str) delete[] str;
  return strTemp;
}

3. 完整调用示例

以下是一个完整的C++调用Python脚本的示例,展示了如何正确传递中文字符:

#pragma execution_character_set("GB2312")
#include <stdlib.h>
#include <Windows.h>   
#include <iostream>
#include <Python.h>
#include <string>
#include <atlstr.h>

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Generic;
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace std;

int main()
{  
  const char* name = "东方红1号";
  Py_Initialize();//初始化python
  PyRun_SimpleString("import sys");
  PyRun_SimpleString("sys.path.append('./')");
  PyObject* pModule = PyImport_ImportModule("hello");
  PyObject* pFunc1 = PyObject_GetAttrString(pModule, "sayhello");   
  PyObject* pArgs = PyTuple_New(1);
  PyObject* pV1 = Py_BuildValue("s", GbkToUtf8(name).c_str());      
  PyTuple_SetItem(pArgs, 0, pV1);
  PyObject* result = PyObject_CallObject(pFunc1, pArgs);
  Py_Finalize();
  return 0;
}

总结

通过设置执行字符集和实现GBK到UTF-8的转换函数,可以有效解决C++调用Python时的中文乱码问题。上述代码示例展示了完整的实现过程,可直接应用于实际项目中。

以上就是解决C++调用Python中文乱码问题的详细内容,更多关于C++与Python交互的资料请关注本站其它相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。