C++调用Python返回中文乱码解决方法

本文介绍在C++中调用Python时,如何处理Python返回含有中文的内容导致的乱码问题。通过PyUnicode_AsWideCharString函数将Unicode对象转换为宽字符字符串,然后转换为char*进行输出。提供了相关的Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工具: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()
{
   
	
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值