Endou Mamoru
Endou Mamoru

Reputation: 43

Python Error:No constructor defined in SWIG generated module of C++ templated code

I'm trying to make a generic stack in C++ and then trying to build a module of it and extend it to Python using SWIG.
For that, code in templated_stack.h is as follows

#include <string>
template <typename T>
class mNode {
public:
    T data;
    mNode* next;
    /* mNode() { } */
    mNode(T d) { 
        data = d;
        next = NULL;
    }

};
template <typename T>
class mStack {
    mNode<T> *topOfStack;
    mStack();   
    void push(T data);
    T pop();
};

template <class T> mStack<T>::mStack() {
    topOfStack = NULL;
}

template <class T> void mStack<T>::push(T data) {
    mNode<T>* newNode = new mNode<T>(data);
    newNode->next = topOfStack;
    topOfStack = newNode;
}

template <class T> T mStack<T>::pop(void) {
    mNode<T>* tempTop = topOfStack;
    T dataToBePopped = tempTop->data;
    topOfStack = topOfStack->next;
    delete tempTop;
    return dataToBePopped;
}

The interface file I've written is templated_stack.i as follows

%module TemplatedStack
%{
        #include <string>
        #include "templated_stack.h"
%}

%include "templated_stack.h"

%template(IntStack) mStack <int>;

And I'm compiling and building module by following script compileScript.sh which has following code

swig -c++ -python -o templated_stack_wrap.cpp templated_stack.i
g++ -c -fPIC templated_stack_wrap.cpp -I/usr/include/python2.7
g++ -shared -o _TemplatedStack.so templated_stack_wrap.o

The module is build successfully and also it is getting imported without any error, But when I try to make an object of IntStack as follows

from TemplatedStack import IntStack
t = IntStack()

I am getting following error

in __init__(self, *args, **kwargs)
     75     __swig_getmethods__ = {}
     76     __getattr__ = lambda self, name: _swig_getattr(self, IntStack, name)
---> 77     def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
     78     __repr__ = _swig_repr
     79     __swig_destroy__ = _TemplatedStack.delete_IntStack

AttributeError: No constructor defined

Any help would be appreciated regarding the above error
Thanks in advance The github link of repository is this

Upvotes: 2

Views: 2161

Answers (1)

This is happening because all your members of the mStack class are private. SWIG can't wrap private things.

Either change the keyword class to struct, or add public: to the definition appropriately.

Upvotes: 2

Related Questions