VC.NET中的String类是利用Unicode字符集编码来表示文本。Unicode字符集中每个字符(汉字、英文字母)都占2个字节,且其字符串是以2个连续的/0结尾的。
ANSI的ASCII字符集是最常见的字符集,常用于表示txt的文本文件。在ASCII字符集中英文占一个字节,汉字2个字节,且其字符串是以一个/0结尾的。
在利用VC.NET进行混合编程时,经常需要实现String与char*的互转,例如在TextBox控件中输入的Text作为fopen或者CreateFile的文件名参数时,常需要实现char*的转化。故提供如下的转化方法:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
int main(array<System::String ^> ^args)
{
// String^ converts to char*
char szDestOutChar[256];
String^ SrcInStr = "C://Documents and Settings//Adiminstrator//我的文档//swq.txt";
int SourceStrLen = SrcInStr->Length;
wchar_t *pwszStr = new wchar_t[SourceStrLen + 1];
array <System::Char>^ pClr = SrcInStr->ToCharArray();
for (int i = 0; i < SourceStrLen; i++)
{
pwszStr[i] = pClr[i];
}
pwszStr[SourceStrLen] = '/0';
::WideCharToMultiByte(CP_ACP, NULL, pwszStr, -1, szDestOutChar, 256, NULL, NULL);
// char* converts to String^
char* szInSrcChar = "C://Documents and Settings//Adiminstrator//我的文档//swq.txt";
int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), NULL, 0);
wchar_t* wszStr = new wchar_t[wcsLen + 1];
::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), wszStr, wcsLen);
wszStr[wcsLen] = '/0';
String^ ClrOutStr = gcnew String(wszStr);
System::Console::WriteLine("Press ENTER key to exit !");
System::Console::Read();
delete pwszStr;
delete wszStr;
return 0;
}