Question

I've been looking at the C++ quick-start guide for msgpack.

http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387

There, there is the following code snippet:

#include <msgpack.hpp>
#include <vector>
#include <string>

class myclass {
private:
    std::string str1;
    std::string str2;
public:
    MSGPACK_DEFINE(str1,str2);
};

int main(void) {
        std::vector<myclass> vec;
        // add some elements into vec...
        /////
        /* But what goes here??? */
        /////

        // you can serialize myclass directly
        msgpack::sbuffer sbuf;
        msgpack::pack(sbuf, vec);

        msgpack::unpacked msg;
        msgpack::unpack(&msg, sbuf.data(), sbuf.size());

        msgpack::object obj = msg.get();

        // you can convert object to myclass directly
        std::vector<myclass> rvec;
        obj.convert(&rvec);
}

I want to serialize a vector of myclass objects.

I've tried the following:

...
vector<myclass> rb;
myclass mc;

...

int main(){
    ...
    mc("hello","world");
    rb.push_back(mc)
    ...
}

But this doesn't work ("error: no match for call")

also, if I do:

mc.str1="hello"
mc.str2="world"

it won't work as str1 and str2 are private.

How to use this MSGPACK_DEFINE(...) macro properly? I can't seem to find anything online.

Many thanks,

Was it helpful?

Solution

MSGPACK_DEFINE() defines some methods implementing packing and unpacking for your class. What you put inside () is a list of the members you want serialized.

After that, you can pack and unpack your class just like you would pack or unpack an int. So the example should be working.

You can try removing the vector and pack only a single object - I think that would simplify it.

OTHER TIPS

class myclass {
    private:
        std::string str1;
        std::string str2;
    public:
        myclass(){};
        myclass(string s1,string s2):str1(s1),str2(s2){};
        MSGPACK_DEFINE(str1,str2);
};

int main(int argc, char **argv)
{
    std::vector<myclass> vec;
    myclass m1("m1","m2");
    vec.push_back(m1);

    // you can serialize myclass directly
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, vec);

    msgpack::unpacked msg;
    msgpack::unpack(&msg, sbuf.data(), sbuf.size());

    msgpack::object obj = msg.get();

    // you can convert object to myclass directly
    std::vector<myclass> rvec;
    obj.convert(&rvec);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top