Interfacing a C++ class, example

Torsten Mohr tmohr at s.netic.de
Wed Mar 10 13:39:11 EST 2004


Hi,

i wrote a short example using "swig" to interface a small C++
class.  It doesn't yet work, as there is not yet an init function:

tmohr at schleim:~/p/python/swig> python
Python 2.3+ (#1, Sep 23 2003, 23:07:16)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pcpl
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: dynamic module does not define init function (initpcpl)
>>>


Can anybody tell me what i need to add to make the C++ class
available in Python as a data type?


Thanks for any hints,
Torsten.


Here are the sources and the Makefile:
MOD = pcpl
PYT = $(MOD).cc


all: $(PYT) pcpl.so


cpl.o: cpl.cc cpl.h
        g++ -o $@ -c $<


$(PYT):
        swig -python -c++ -o $@ -module $(MOD) cpl.h


pcpl.o: wpcpl.cc pcpl.cc cpl.h
        g++ -o $@ -c $< -I/usr/include/python2.3


pcpl.so: pcpl.o cpl.o
        gcc -Bdynamic -shared -o $@ $^



clean:
        -rm -f pcpl.so
        -rm -f pcpl.o
        -rm -f cpl.o
        -rm -f pcpl.cc
        -rm -f pcpl.h
        -rm -f pcpl.py




### cpl.h
#ifndef CPL_H
#define CPL_H 1

class Abc {
        public:
                Abc();
                ~Abc();

                int somefunc(int a);
};

#endif





### cpl.cc
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include "cpl.h"

using namespace std;


Abc::Abc() {
        cout << "Abc()" << endl;
}

Abc::~Abc() {
        cout << "~Abc()" << endl;
}

int Abc::somefunc(int a) {
        cout << "a is " << a << endl;

        return 42;
}




### wpcpl.cc
#include "cpl.h"
#include "pcpl.cc"






More information about the Python-list mailing list