0

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

Thanks

3
  • "python dictionary stored in a file" - how did you store it? cPickle, json? Commented Oct 19, 2010 at 7:48
  • neither, it is written using a print statement to a file Commented Oct 19, 2010 at 9:54
  • Without any examples or sample code showing how you wrote it, we have nothing much to say. Please post your code. Commented Oct 19, 2010 at 10:16

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.