1

I used swig to wrap some C++ Api to Python.

The c++ api looks like this.

class CThostFtdcMdSpi
{
public:
virtual void OnFrontConnected(){};
virtual void OnFrontDisconnected(int nReason){};
virtual void OnHeartBeatWarning(int nTimeLapse){};
...
};

class MD_API_EXPORT CThostFtdcMdApi
{
public:
static CThostFtdcMdApi *CreateFtdcMdApi();
virtual void RegisterSpi(CThostFtdcMdSpi *pSpi) = 0;
...
}

MdSpi defines some callback function behaviors. MdApi need to call RegisterSpi(CThostFtdcMdSpi *pSpi) to register those callback functions This is how I want to use this in python

class Quote(CThostFtdcMdSpi):
def OnFrontConnected(self):
    pass

def OnFrontDisconnected(self, *args):
    pass

md = CThostFtdcMdApi_CreateFtdcMdApi()
q = Quote()
md.RegisterSpi(q)

Python gave this error message:

def RegisterSpi(self, *args): return _MdApi.CThostFtdcMdApi_RegisterSpi(self, *args)
TypeError: in method 'CThostFtdcMdApi_RegisterSpi', argument 2 of type 'CThostFtdcMdSpi *'

This is my MdApi.i. Both MdApi and MdSpi are defined in ThostFtdcMdApi.h

%module MdApi
%{
#include "ThostFtdcMdApi.h"
%}

%feature("director") CThostFtdcMdSpi;
%feature("director") CThostFtdcMdApi;

%include "ThostFtdcMdApi.h"
Crazymooner
  • 231
  • 1
  • 3
  • 11
  • 1
    It's hard to tell without more code, but this looks like it could be something related to http://stackoverflow.com/questions/16840706/use-method-inherited-from-abtract-c-class-in-a-python-class-swig ... If so, try defining `__init__`, and calling your super constructor. – ftwl Jun 30 '14 at 09:15
  • The first part of my answer: http://stackoverflow.com/questions/9040669/how-can-i-implement-a-c-class-in-python-to-be-called-by-c/9042139#9042139 should be a fully worked example of this. – Flexo Jun 30 '14 at 12:06
  • Have you tried using `%feature("director")` as described in the SWIG docs and as shown in the SWIG example that come with the distro? Please show the .i file you used. – Oliver Jul 01 '14 at 04:04
  • @Flexo I use % feature("director"), but error still exist. – Crazymooner Jul 01 '14 at 06:48
  • @Schollii I uploaded my .i file as well. am I using it in a wrong fashion? – Crazymooner Jul 01 '14 at 06:49

1 Answers1

0

It looks like you're missing enabling directors at the module level. The first line of your .i file needs to be:

%module(directors="1") MdApi

From the directors documentation:

The director feature is disabled by default. To use directors you must make two changes to the interface file. First, add the "directors" option to the %module directive, like this:

%module(directors="1") modulename

Without this option no director code will be generated. Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors.

Flexo
  • 87,323
  • 22
  • 191
  • 272