CString无效*

时间:2013-01-10 10:24:22

标签: c++ windows type-conversion void-pointers cstring

是否可以将CString转换为void*。我制作了一个无效指针并将其指向某个对象。现在我将其保存在CString中。现在,我想从void*转换回CString

void* pPointer = &SomeObject;
CString myString;
myString.Format(_T("%x"), pPointer);

//void* anotherPointer = (void*)myString;

4 个答案:

答案 0 :(得分:3)

这是不可能的。

您可以做的是将CString*转换为void*

void* anotherPointer = (void*) & myString;

并返回:

CString* pToMyString = (CString*) anotherPointer;

答案 1 :(得分:2)

你不能“转换” CStringvoid*,但你可以“转换” CString* (即{strong>指针到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;
}

答案 2 :(得分:0)

你格式化字符串的方式似乎是错误的。 %d 适用于整数,因此会将 void * 地址格式化为数字。如果这真的是你想要的,你可以解析字符串以获得它包含的数字,然后将其转换为 void * 。但我很确定这不是你想要的。

答案 3 :(得分:0)

如果打算使用CString的内容(即写入文件),则需要使用GetBuffer函数来访问实际内容。

void playTone() {
    long elapsed_time = 0;
    if (tone_ > 0) { // if this isn't a Rest beat, while the tone has 
                     //  played less long than 'duration', pulse speaker HIGH and LOW
        while (elapsed_time < duration) {

            digitalWrite(speakerOut, HIGH);
            delayMicroseconds(tone_ / 2);

            // DOWN
            digitalWrite(speakerOut, LOW);
            delayMicroseconds(tone_ / 2);

            // Keep track of how long we pulsed
            elapsed_time += (tone_);
        }
    }
    else { // Rest beat; loop times delay
        for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
            delayMicroseconds(duration);
        }
    }
}

void loop() {
    // Set up a counter to pull from melody[] and beats[]
    for (int i = 0; i<MAX_COUNT; i++) {
        tone_ = melody[i];
        beat = beats[i];

        duration = beat * tempo; // Set up timing

        playTone();
        // A pause between notes...
        delayMicroseconds(pause);

    }
}