解決c++調(diào)用python中文亂碼問題
windows中文操作系統(tǒng)下,vs的c++項目默認(rèn)編碼是GB2312
python默認(rèn)是utf-8編碼
最好在c++程序頂上加:
#pragma execution_character_set("GB2312")
c++中的字符串一定就是gbk編碼
傳入python前要做編碼轉(zhuǎn)換
準(zhǔ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)文章
利用Python的tkinter模塊實現(xiàn)界面化的批量修改文件名
這篇文章主要介紹了利用Python的tkinter模塊實現(xiàn)界面化的批量修改文件名,用Python編寫過批量修改文件名的腳本程序,代碼很簡單,運行也比較快,詳細(xì)內(nèi)容需要的小伙伴可以參考一下下面文章內(nèi)容2022-08-08
淺談numpy中l(wèi)inspace的用法 (等差數(shù)列創(chuàng)建函數(shù))
下面小編就為大家?guī)硪黄獪\談numpy中l(wèi)inspace的用法 (等差數(shù)列創(chuàng)建函數(shù))。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
利用Pycharm + Django搭建一個簡單Python Web項目的步驟
這篇文章主要介紹了利用Pycharm + Django搭建一個簡單Python Web項目的步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
matplotlib基礎(chǔ)繪圖命令之bar的使用方法
這篇文章主要介紹了matplotlib基礎(chǔ)繪圖命令之bar的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
Python錯誤提示:[Errno 24] Too many open files的分析與解決
這篇文章主要給大家介紹了Python中出現(xiàn)錯誤提示:[Errno 24] Too many open files的分析與解決,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02

