[C++-sig] Why this does not work- overriding C++ virtual functions in python script?

Bruce Who bruce.who.hk at gmail.com
Tue May 8 14:20:54 CEST 2007


Hi, all

I have managed to get a python wrapper for my Cpp modules, but there
is something wrong.

This is my cpp files:

// cmod.h file
#ifndef __CMOD_H
#define __CMOD_H

class EventHandler
{
public:
    virtual void OnEvent(){}
    virtual ~EventHandler(){}
};

void func(void);

void setEventHandler(EventHandler* pEH);

#endif

// cmod.cpp file
#include "cmod.h"

static EventHandler* s_pEH;

void func(void)
{
    if(s_pEH != NULL)
    {
        printf("call OnEvent");
        s_pEH->OnEvent();
    }
}

void setEventHandler(EventHandler* pEH)
{
    s_pEH = pEH;
}

// cmod.i file
%module cmod
%include "cmod.h"


%inline %{
#include "cmod.h"

%}


and I compile all these files with Visual Studio 2005:

swig -c++ -python cmod.i
cl -c cmod_wrap.cxx -ID:\program\Python25\include\
cl -c cmod.cpp
link /subsystem:windows /LIBPATH:D:\program\Python25\libs\
cmod_wrap.obj cmod.obj /dll /OUT:_cmod.pyd

and then we can get cmod.py and _cmod.pyd. I write a python script:

# testcmod.py file
import cmod

class EventHandler(cmod.EventHandler):
    def OnEvent(self):
        print 'called'

eh = EventHandler()
cmod.setEventHandler(eh)
cmod.func()


Once this script runs, it is supposed to print 'called' but it does
not! I guess that if we cannot override C++ virtual functions in
python script? Hope someone can help me. Any help would be
appreciated!


Bruce



More information about the Cplusplus-sig mailing list