工具:VS2019 PyCharm python3.92版本
C++调用Python时,Python返回中带有中文,调试输出时出现乱码解决方法
关于C++调用Python返回中文乱码的解决问题,我在网上找了好多,但都没有找到我想要的(可能是我的检索词不太对,所以收不到),诶!好不容易找到两篇,有一篇却是从C++中传中文给Python的:https://www.jb51.net/article/192022.htm
对于Python返回的中文解决却没有,但这也是一个很好的例子,最符合我的是这位博主写的这篇:https://blog.youkuaiyun.com/qq_33775402/article/details/57412102
但他这篇的大部分函数因为Python的更新换代,失效了!这让很懒的我很是抓狂,也幸好,有了他这篇的启示,只要耐心在python官方手册里翻,还是能翻到的,功夫不负有心人(主要是我懒,懒得去找),终于在官方手册里找到了一个:
wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
Convert the Unicode object to a wide character string. The output string always ends with a null character. If size is not NULL, write the number of wide characters (excluding the trailing null termination character) into size. Note that the resulting wchar_t string might contain null characters, which would cause the string to be truncated when used with most C functions. If size is NULL and the wchar_t string contains null characters a ValueError is raised.
Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) on success. On error, returns NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.
3.2 新版功能.
在 3.7 版更改: Raises a ValueError if size is NULL and the wchar_t* string contains null characters.
这个函数会返回一个宽字节指针类型的变量,嘿嘿,这个不就很香吗?再结合API函数把 wchar_t* 转换为 char* 不就可以输出了?呵呵,说了这么一大堆,估计看得人都烦,上代码:
#include "iostream"
#include "windows.h"
#include "python.h"
int main()
{