CLR std::string和system::String互转(Windows7 utf-8编码)

花了我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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值