解决c++调用python中文乱码问题
程序员文章站
2022-08-10 19:38:22
windows中文操作系统下,vs的c++项目默认编码是gb2312python默认是utf-8编码最好在c++程序顶上加:#pragma execution_character_set("gb231...
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中文乱码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
Three.js使用THREE.TextGeometry创建三维文本中文乱码的问题如何解决?
-
布同 Python中文问题解决方法(总结了多位前人经验,初学者必看)
-
解决asp.net core在输出中文时乱码的问题
-
解决3.01版的jquery.form.js中文乱码问题的解决方法
-
C++ 调用Python3 脚本中无法引入内建模块的问题解决方法
-
Python遍历zip文件输出名称时出现乱码问题的解决方法
-
解决Python中list里的中文输出到html模板里的问题
-
解决python3 HTMLTestRunner测试报告中文乱码的问题
-
通过过滤器(Filter)解决JSP的Post和Request中文乱码问题
-
JSP利用过滤器解决request中文乱码问题