SWIG ignores the conversion operators. But is there a way to fake the behaviour of a conversion operator?


Thanks in advance,




For illustration, some example code for my problem:


>>> import conv_test as ct

>>> b=ct.B()

>>> ct.print_a(b) # Throws: TypeError: in method 'print_a', argument 1 of type 'test::A const &'


with the following source files:



#ifndef __conv_test_h

#define __conv_test_h

#include <iostream>

namespace test {

    class A // Just a class

    {    };

    class B // Owns an A, and should be useable like an A


        A* a;


        B() : a(new A) {}

        A& get_A() {return *a;}

        ~B() { delete a; std::cout << " B deleted" << std::endl;}


       // Conversion operators

       operator test::A&() {return *a;}

        operator const test::A&() const {return *a;}


    // Function expecting an A, should work with a B, too

    void print_a(const test::A& a)


        std::cout << "A printed" << std::endl;       


    // Proof for the working conversion operator on the C++ side

    void print_b(const B& b)









conv_test.i :

%module conv_test


#include "conv_test.h"


%include "conv_test.h"