Wrap a C++ member vector as a Python OrderedDict

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Wrap a C++ member vector as a Python OrderedDict

giumas
I have a class similar to this:

    #include <vector>
    #include <utility>
    #include <string>
   
    class Test
    {
    public:
    std::vector<std::pair<std::string, std::string>> a;
        bool read(const std::string& path);
        bool write(const std::string& path);
    }

and I want to modify the setter and the getter created by Swig for Python so that I can get/set an ordered dictionary.

Currently, using the following in the interface file:

    %include "stl.i"
   
    %template(string_pair) std::pair<std::string, std::string>;
    %template(string_pair_vec) std::vector< std::pair<std::string, std::string>>;

I can write Python code like:

    from collections import OrderedDict
   
    t = Test()
    d = OrderedDict(t.a)
    t.a = string_pair_vec([(k,v) for k,v in d.items()])

So, when the OrderedDict is modified, the user has to proper manage `t.a` to reflect the changes.. so I think that it might be better to manage these operations directly in the SWIG generated code.

From my current understanding, if I was dealing with a simple `dict`, I could have done it by using `typemap` (something like this: http://stackoverflow.com/q/16527174/2741329), but `OrderedDict` is implemented in pure Python.

So my current intuition is that I have to use something like this in my interface file:

    %pythonappend Test::a %{
       #Code to create and populate the ordered dict
    %}

but the above signature does not work (or, better, I don't know how to identify the setter and the getter).
I have asked the same question on SO without luck: http://stackoverflow.com/q/40952921/2741329 !

Does somebody have experience with something like this?
Loading...