使用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();