欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決c++調(diào)用python中文亂碼問題

 更新時間:2020年07月29日 09:38:33   作者:whwqs  
這篇文章主要介紹了c++調(diào)用python中文亂碼問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

windows中文操作系統(tǒng)下,vs的c++項目默認編碼是GB2312

python默認是utf-8編碼

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

#pragma execution_character_set("GB2312")

c++中的字符串一定就是gbk編碼

傳入python前要做編碼轉(zhuǎn)換

準備一個gbk轉(zhuǎn)utf8的函數(shù),如下(網(wǎng)上的):

 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;

到此這篇關(guān)于解決c++調(diào)用python中文亂碼問題的文章就介紹到這了,更多相關(guān)c++調(diào)用python中文亂碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論