欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 使用pybind11开发c++扩展模块输出到控制台的中文信息显示乱码的问题

使用pybind11开发c++扩展模块输出到控制台的中文信息显示乱码的问题

2025/4/16 14:44:50 来源:https://blog.csdn.net/yivifu/article/details/147164181  浏览:    关键词:使用pybind11开发c++扩展模块输出到控制台的中文信息显示乱码的问题

使用pybind11开发供Python项目使用的C++扩展模块时,如果在扩展模块的C++代码中向控制台输出的信息中包含中文,python程序的控制台很容易出现乱码。以如下C++扩展框架代码为例(这是对上一篇文章简明使用pybind11开发pythonc+扩展模块教程-CSDN博客中的C++扩展框架代码进行少量修正后的结果):

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <locale>
#include <codecvt>
#include <windows.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>namespace py = pybind11;class CSVFinder {
private:std::map<std::string, std::vector<std::string>> dataMap;std::vector<std::string> headers;public:// 默认构造函数CSVFinder() {}// 接受 CSV 文件路径的构造函数CSVFinder(const std::string& filePath) {loadCSV(filePath);}// 载入 CSV 文件的方法void loadCSV(const std::string& filePath) {// 检查文件扩展名是否为 .csvif (filePath.substr(filePath.find_last_of(".") + 1) != "csv") {std::cerr << "文件扩展名不是 .csv,但仍尝试解析: "  << filePath << std::endl;}std::ifstream file(filePath);if (!file.is_open()) {std::cerr << "无法打开文件,请检查文件名或路径是否错误: " << filePath <<  std::endl;dataMap.clear();headers.clear();return;}std::string line;// 读取第一行作为标题if (!std::getline(file, line)) {std::cerr << "无法读取文件的第一行,请检查文件内容: " << filePath << std::endl;dataMap.clear();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词