通过消息队列按地址设置指针的值

时间:2019-04-03 20:38:50

标签: c++ pointers

我试图声明一个向量指针,然后让它引用在对象中找到的向量。这只是很复杂,因为我必须通过消息队列系统发送它。消息队列仅知道如何处理int,因此我唯一可以传递的是将地址转换为int。处理邮件时,必须将其转换回向量指针,然后设置其值。

我在这里有一个微型问题,以同样的方式失败了。在这种情况下,“消息队列”为GetItems,而“消息处理器”为GetItemsPrivate

失败是因为在处理完成之后指针值仍然为0,即使我通过队列获得了一个不错的地址,我似乎还是在错误地转换为向量指针。

#include <string>
#include <iostream>
#include <vector>

class Box {
    public:
        std::string name;
        Box(std::string name);
        ~Box();
};
Box::Box(std::string name)
    :name(name)
{

}
Box::~Box(){}

class Item {
    public:
        std::string name;
        Box *box;
        Item(std::string name, Box *box);
        ~Item();
        void Print();
};
Item::Item(std::string name, Box *box)
:name(name),
 box(box)
{

}
Item::~Item(){}
void Item::Print(){
    std::cout << "Item name: " << name << std::endl;
    std::cout << "Item box: " << box->name << std::endl;
}

class Foo {
    private:
        void GetItemsPrivate(uint64_t item_ptr);
    public:
        std::vector<Item*> items;  
        Foo();
        ~Foo();
        void GetItems(std::vector<Item*> *&your_items);
};
Foo::Foo(){}
Foo::~Foo(){}
void Foo::GetItemsPrivate(uint64_t item_ptr){
    // pretend message receiver where ptr address is unpacked and then set 
    std::cout << "GetItemsPrivate param value 0x" << std::hex << item_ptr << std::endl;
    std::vector<Item*> *your_items = (std::vector<Item*> *)item_ptr;
    std::cout << "GetItemsPrivate ptr value " << your_items << std::endl; // should be 0 
    std::cout << "GetItemsPrivate ptr address " << &your_items << std::endl; // should be same address from main 
    // set the ptr to the map 
    your_items = &items;
}
void Foo::GetItems(std::vector<Item*> *&your_items){
    std::cout << "GetItems value " << your_items << std::endl;
    std::cout << "GetItems address " << &your_items << std::endl;
    // pretend message queue system where address must be shipped in a message
    GetItemsPrivate((uint64_t)&your_items);
}

void PrintItems(std::vector<Item*> *items){
    for(int i = 0; i < items->size(); i++){
        (*items)[i]->Print();
    }
}

int main()
{
    Box *boxA = new Box("BoxA");
    Item *itemA = new Item("Item A", boxA);

    Box *boxB = new Box("BoxB");
    Item *itemB = new Item("Item B", boxB);

    Foo foo;
    foo.items.push_back(itemA);
    foo.items.push_back(itemB);

    std::vector<Item*> *my_items = 0; 
    std::cout << "main value of my_items is " << my_items << std::endl;
    std::cout << "main address of my_items is " << &my_items << std::endl;

    foo.GetItems(my_items);
    // at this point, ptr should point to Foo's item vector
    std::cout << "main value of my_items is " << my_items << std::endl;

    //PrintItems(my_items);

    return 0;
}

输出

  

my_items的主值为0
  my_items的主要地址是0x7ffe61b0c2f8
  GetItems值0
  GetItems地址0x7ffe61b0c2f8
  GetItems私有参数值0x7ffe61b0c2f8
  GetItems私人ptr值0x7ffe61b0c2f8
  GetItems私人ptr地址0x7ffe61b0c288
  my_items的主要值为0

0 个答案:

没有答案