您不能将a “转换”CString
为 a void*
,但您可以将a (即指向 a 的指针)“转换”为 a :CString*
CString
void*
// Create a CString object
CString str(_T("Foo"));
// Store CString address in a void* pointer
void* ptr = &str;
// Cast from void* back to CString*
CString* pstr = static_cast<CString*>(ptr);
// Print CString content
_tprintf(_T("%s\n"), pstr->GetString());
但是,您似乎在做一些不同的事情:即将某个对象的地址(指针)作为整数格式的字符串存储到CString
. 然后你需要从字符串中取回整数值,使用一些解析函数,比如_tcstoul()
. 这似乎有效,但需要更多测试:
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <string>
#include <atlbase.h>
#include <atldef.h>
#include <atlstr.h>
using namespace std;
using namespace ATL;
// Some test class
struct MyClass
{
string Foo;
int Bar;
MyClass(const string& foo, int bar)
: Foo(foo), Bar(bar)
{}
};
// Test
int main()
{
// Create some object
MyClass c("A foo", 10);
// Get the address of the object
void* ptr = &c;
// Format the address into a string
CString str;
str.Format(_T("%p"), ptr);
// Parse the address from string
void* ptr2 = reinterpret_cast<void*>( _tcstoul( str.GetString(), nullptr, 16 ) );
// Get back the original MyClass pointer
MyClass* pMyClass = static_cast<MyClass*>(ptr2);
// Check result
cout << pMyClass->Foo << endl;
cout << pMyClass->Bar << endl;
}