当前位置: 移动技术网 > IT编程>脚本编程>Python > 解决c++调用python中文乱码问题

解决c++调用python中文乱码问题

2020年07月30日  | 移动技术网IT编程  | 我要评论

windows中文操作系统下,vs的c++项目默认编码是gb2312

python默认是utf-8编码

最好在c++程序顶上加:

#pragma execution_character_set("gb2312")

c++中的字符串一定就是gbk编码

传入python前要做编码转换

准备一个gbk转utf8的函数,如下(网上的):

 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;
    }

示例性代码:

#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;

到此这篇关于解决c++调用python中文乱码问题的文章就介绍到这了,更多相关c++调用python中文乱码内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网