开发者

Read python dictionary using c++

I have a python dictionary stored in a file which I need to access from a c++ program. What 开发者_JAVA技巧is the best way of doing this?

Thanks


How to do this depends on the python types you've serialised. Basically, python prints something like...

{1: 'one', 2: 'two'}

...so you need code to parse this. The simplest case is a flat map from one simple type to another, say int to int:

int key, value;
char c;

if (s >> c && c == '{')
    while (s >> key)
    {
        if (s >> c && c == ':' && s >> value)
            my_map[key] = value;
        if (s >> c && c != ',')
            break;
    }

You can build on this, adding parsing error messages, supporting embedded containers, string types etc..

You may be able to find some existing implementation - I'm not sure. Anyway, this gives you a very rough idea of what they must do internally.


There are umpteen Python/C++ bindings (including the one in Boost) but I suggest KISS: not a Python/C++ binding but the principle "Keep It Simple, Stupid".

Use a Python program to access the dictionary. :-)

You can access the Python program(s) from C++ by running them, or you can do more fancy things such as communicating between Python and C++ via sockets or e.g. Windows "mailslots" or even some more full-fledged interprocess communication scheme.

Cheers & hth.


I assume your Python dict is using simple data types and no objects (so strings/numbers/lists/nested dicts), since you want to use it in C++.

I would suggest using json library (http://docs.python.org/library/json.html) to deserialize it and then use a C++ equivalent to serialize it to a C++ object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜