注意在转换CString到char*时用LPCTSTR
字符串转换相关的。也转了部分。整理成库。
[code]
// MFCConver.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "MFCConver.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#include "PStringConv.h"
#include <stdlib.h>
#include <string>
#include <atlbase.h>
#include <atlstr.h>
#using <mscorlib.dll>
// 唯一的应用程序对象
CWinApp theApp;
using namespace std;
using namespace System;
//CLI class
__abstract __gc class Base
{
int BaseFunction() { return 0; }
};
__gc class Derived : public Base
{
};
void toString(CString &str, LPTSTR *result)
{
*result = str.GetBuffer();
}
void toUse(const WORD *charb)
{
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// 初始化 MFC 并在失败时显示错误
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: 更改错误代码以符合您的需要
_tprintf(_T("致命错误: MFC 初始化失败\n"));
nRetCode = 1;
}
else
{
PStringConv tStr;
//char*
char *orig = "Hello World";
LPCTSTR lp = "Microsoft";
CString tString = "Microsoft GoodLuck";
lp = (LPCTSTR)tString;
cout<<lp<<endl;
cout<<orig<< " (char *)" <<endl;
// 转换到 wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedchars = 0;
wchar_t wcstring[newsize];
mbstowcs(wcstring, orig, origsize);
wcscat(wcstring, L"(wchar_t *)");
wcout<<wcstring <<endl;
//转换到_bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout<<bstrt<<endl;
//转换到 CComBSTR
CComBSTR ccombstr(orig);
if(ccombstr.Append(L"(CComBSTR) ") == S_OK)
{
CW2A printstr(ccombstr);
cout<<printstr<<endl;
}
//转换到 CString
CString cstring(orig);
cstring += "(CString)";
cout<<cstring<<endl;
//Convert to a basic_string
string basicstring(orig);
basicstring += "(basic_string)";
cout<<basicstring<<endl;
//转化为托管的 System串?
#pragma push_macro("new")
#undef new
String *systemstring = __gc new String(orig);
Console::WriteLine("{0}", systemstring);
#pragma pop_macro("new")
}
return nRetCode;
}
[/code]
浙公网安备 33010602011771号