花了我3天时间,Google搜索了大量的文章。CLR写的dll工程的属性是"使用多字节字符集",sqlite3里面存储的同样是多字节。在Windows10上运行毫无异常,在Windows7上运行就是乱码。中间我还给win7系统更新了字体,效果是乱码变了,或者字符串前面少一截。
System::String 转 std::string;
#pragma once
#include <msclr\marshal_cppstd.h> //这个头文件要放到最前面,不然编译会报错/
public: char* GetCString(System::String^ text)
{
// get unsigned char array from System::String
cli::array<wchar_t> ^chArray = text->ToCharArray();
cli::array<unsigned char, 1> ^arr = System::Text::Encoding::UTF8->GetBytes(chArray);
// declare a C array
char *c_arr = new char[arr->Length + 1];
memset(c_arr, NULL, arr->Length + 1);
System::IntPtr c_arr_ptr(c_arr);
// copy from .NETs unsigned char array to char array
System::Runtime::InteropServices::Marshal::Copy(arr, 0, c_arr_ptr, arr->Length);
return c_arr;
}
std::string 转 System::String ,这个函数感谢一篇日语博客。
public: System::String^ stdStrToUnicode(string cpp_string)
{
array<unsigned char>^ c_array = gcnew array<unsigned char>(cpp_string.length());
for (int i = 0; i < cpp_string.length(); i++)
{
c_array[i] = cpp_string[i];
}
System::Text::Encoding^ u8enc = System::Text::Encoding::UTF8;
System::String^ u8_array = u8enc->GetString(c_array);
return u8_array;
}
然后在传回c# WPF就可以正常显示了。
#C++写日志存文件
#include<iostream>
#include<sstream>
#include<fstream>
using namespace std;
ofstream fout("C:\\outtxt.txt", std::ofstream::app);
fout<< "Bit2string#" << strbit <<endl;
fout<<endl;
fout<<flush;
fout.close();