Vadim Lebedev
Vadim Lebedev

Reputation: 191

Using SWIG to wrap C++ class with virtual methods and overriding them in python

I'm trying to "pythonize" method arguments when calling python callback:


    %module (directors="1") py_test
    %feature("director") mgr;


    struct hdr_val {
        const char *hdr;
        const char *val;
    };

    struct hdr_list {
        int count;
        struct hdr_val *elems;
    };


    struct myinfo {
      int   newcid;                
      int   oldcid;                
      const char *uri;    
      struct hdr_list hlist;
    };

    %{
    PyObject*
    make_hdrlist(const struct hdr_list *hl) {
      PyObject* result;

      result = PyList_New(hl->count);
      for(int i = 0; i count; i++)
         PyList_SetItem(result, i, Py_BuildValue("(ss)", hl->elems[i].hdr, hl->elems[i].val));

      return result;    
    }
    %}


    class mgr {
    public:
       mgr() { }
       virtual void doit();

       virtual void done(const struct myinfo* i)  // Will be redefined in python 
       { 
       }
    };

    %typemap(out) struct myinfo* i {

        $result = Py_BuildValue("(iiso)", $1->newcid, $1->oldcid, $1->uri, make_hdrlist(&$1->hlist));

    }

so that in python I'll be able to do the following:


    import py_test
    class pymgr(py_test.mgr):
       def done(self, info):
         oldcid,newcid,uri,hlist = info

E.g., I want the info argument in python to be a tuple("iiso") and not Swig wrapper object.

Unfortunatley SWIG ignores my typemap(out) for some reason. Any ideas?

Upvotes: 1

Views: 1586

Answers (1)

Vadim Lebedev
Vadim Lebedev

Reputation: 191

Ok I've found the answer The typemap should be placed BEFORE class mgr

%typemap(directorin) myinfo const * {
    $input = Py_BuildValue("(iiso)", $1_name->newcid, $1_name->oldcid, 
                           $1_name->uri, make_hdrlist(&$1_name->hlist));
}

Upvotes: 1

Related Questions