2007年05月15日 星期二 08:41
Hi, 我把swig自带的callback例子做了个修改,发现运行有错,请大家帮忙看下。 原来的callback例子是能编译通过并正常运行的,唯一的改动就是给回调函数加了个参数。下面是全部的代码: // ================== example.h #include#include class Callback { public: virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; } // virtual void run() { std::cout << "Callback::run()" << std::endl; } virtual void run(int* pn) { std::cout << "Callback::run()" << (*pn) << std::endl; } }; class Caller { private: Callback *_callback; public: Caller(): _callback(0) {} ~Caller() { delCallback(); } void delCallback() { delete _callback; _callback = 0; } void setCallback(Callback *cb) { delCallback(); _callback = cb; } // void call() { if (_callback) _callback->run(); } void call() { if (_callback) { int i = 90; _callback->run(&i;); } } }; // ================== example.cxx #include "example.h" // ================== example.i %module(directors="1") example %{ #include "example.h" %} %include "std_string.i" %feature("director") Callback; %include "example.h" @rem ================== build.bat @rem I compile my code with this bat file set FILENAME=example call "D:\program\Microsoft Visual Studio 8\VC\bin\vcvars32" swig -c++ -python %FILENAME%.i cl -c %FILENAME%_wrap.cxx -ID:\program\Python25\include\ link /subsystem:windows /LIBPATH:D:\program\Python25\libs\ %FILENAME%_wrap.obj /dll /OUT:_%FILENAME%.pyd #=================================================== # file: runme.py # you can test the wrapper with this script import example class PyCallback(example.Callback): def __init__(self): example.Callback.__init__(self) def run(self, i): print "PyCallback.run()", i # Create an Caller instance caller = example.Caller() # Add a simple C++ callback (caller owns the callback, so # we disown it first by clearing the .thisown flag). print "Adding and calling a normal C++ callback" print "----------------------------------------" callback = example.Callback() callback.thisown = 0 caller.setCallback(callback) caller.call() caller.delCallback(); print print "Adding and calling a Python callback" print "------------------------------------" # Add a Python callback (caller owns the callback, so we # disown it first by calling __disown__). caller.setCallback(PyCallback().__disown__()) caller.call() caller.delCallback() print print "Adding and calling another Python callback" print "------------------------------------------" # Lets do the same but use the weak reference this time. callback = PyCallback().__disown__() caller.setCallback(callback) caller.call() caller.delCallback() # All done. print print "python exit" 在命令行上运行: E:\test>runme.py Adding and calling a normal C++ callback ---------------------------------------- Callback::run()90 Callback::~Callback() Adding and calling a Python callback ------------------------------------ PyCallback.run() 然后出错对话框弹出来说"python.exe遇到问题需要关闭。我们对此引起的不便表示抱歉。"
Zeuux © 2025
京ICP备05028076号