views:

59

answers:

1

SWIG doesn't wrap inherited static functions of derived classes. How it can be resolved?

Here is a simple illustration of the problem.

This is a simple C++ header file:

// file test.hpp
#include <iostream>

class B
{
public:
  static void stat()
  { std::cerr << "=== calling static function B::stat" << std::endl; }

  void nonstat() const
  { std::cerr << "==== calling B::nonstat for some object of B" << std::endl; }
};

class D : public B {};

The C++ source file just includes the header file:

// file test.cpp
#include "test.hpp"

The SWIG interface file just includes the C++ header file:

// file test.swig
%module test
%{
#include "test.hpp"
%}

%include "test.hpp"

Then I generate the swig wrapper code by this:

swig -c++ -tcl8 -namespace main.swig

And then I create a shared library by this:

g++ -fpic -Wall -pedantic -fno-strict-aliasing \
               test.cpp test_wrap.cxx -o libtest.so

So when loading libtest.so in a tcl interpretor and trying to use the wrapped interface, it has the following behavior:

% load libtest.so test
% test::B b
% test::D d
% b nonstat    # works fine
% d nonstat    # works fine
% test::B_stat # works fine
% test::D_stat # DOESN'T WORK !!

So the question is how can i make SWIG to wrap D::stat?

+1  A: 

The static function is only defined in the parent class B correct? as in:

D::stat();

Is not callable correct? Thats why SWIG doesn't wrap the function...

As to how you can get access to the function, SWIG allows you to add/hide/wrap functions from any class you want to, so it would be possible to "fix" the SWIG class to give access to stat().

Believe the syntax is something like:

%extend D {
   ...
}

Its been a while since I touched SWIG so I might be misremembering something.

Petriborg
Thanks for answer Petriborg. In C++ D::stat() is callable, as there is a public function B::stat() and D publicly inherits from B. The issue is that SWIG doesn't wrap D::stat().If using %extend, I have to rewrite stat:%extend D { static void stat() { B::stat(); }}This fixes the problem, (i.e. I will be able to call % test::D_stat then), but this is a workaround; I mean I am writing code which I shouldn't; SWIG could handle it automatically; I will go this way only if I know that there is no better way.SWIG experts, please suggest other ways (or say that there is no better way)!
Vahagn
I was unaware that in C++ you could call the child class's static methods that way, interesting. It might be a work around, but I guess I'm not surprised that this happens. In Java you don't inherit static methods IIRC either. *shrug*.
Petriborg