tssch
tssch

Reputation: 764

How can I wrap operator+ function with swig?

I am trying to wrap the operator+ function of the btVector3 class of the bullet lib. operator+ is not defined as a class member, but as a function.

Wrapping operator+= which is a class method is working fine. If I declare the operator+ in the swig interface file (which I can only do outside of the class definition) swig does not recognize this as an operator belonging to the class.

I tried to use extend:

%extend btVector3
{
    btVector3 __add__(const btVector3& v1, const btVector3& v2) { return operator+(v1, v2); }  
};

This leads to swig generating the python __add__ method for btVector3. I do however get the following runtime error:

AttributeError: 'module' object has no attribute 'btVector3___add__'

Upvotes: 2

Views: 836

Answers (1)

The problem with your attempt is that the generated __add__ function is non-static and thus actually takes 3 arguments: (self, v1, v2).

Ordinarily you could just make something like that static in C++ if you wanted to drop the self/this argument. That didn't seem to work in my testing with SWIG/Python just now. I think this is because class scope functions in Python, even when called with a specific instance rather than without an instance don't get the self parameter passed in, so it would end up missing an argument.

The solution is to write it the %extend version of __add__ as a regular old member function. A minimal example:

%module test

%inline %{
 struct btVector3 {
   double v[3];

   btVector3 add_vec(const btVector3& b) {
     // Or call your other operator here instead.
     btVector3 ret;
     for (int i = 0; i < 3; ++i)
       ret.v[i] = v[i]+b.v[i];
     return ret;
   }

 };
%}

%extend btVector3 {
 btVector3 __add__(const btVector3& b) {
   btVector3 ret;
   for (int i = 0; i < 3; ++i)
     ret.v[i] = $self->v[i]+b.v[i];
   return ret;
 }
}

Which is sufficient to allow me do use it like:

import test

print(dir(test))

a=test.btVector3()
b=test.btVector3()
c=a+b
print(c)

Upvotes: 1

Related Questions