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

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

本文详细解析了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 相关产品和应用

全部下载

专题列表