Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beazley D.M.SWIG users manual.pdf
Скачиваний:
14
Добавлен:
23.08.2013
Размер:
1.53 Mб
Скачать

SWIG Users Guide

SWIG and Python

206

 

 

 

print "Making plot3.gif...

"

w2 = PlotWidget(500,500,-7,-1.5,7,1.5)

w2.set_pymethod(sin)

# Register sin(x) as a callback

w2.plot()

f = open("plot3.gif","w") w2.save(f)

f.close()

The “plot” method for each widget is written entirely in C++ and assumes that it is calling a callback function written in C/C++. Little does it know that we have actually implemented this function in Python. With a little more work, we can even write a simple function plotting tool :

# Plot a function and spawn xv

import posix import sys import string

from plotwidget import * from math import *

line = raw_input("Enter a function of x : ")

ranges = string.split(raw_input("Enter xmin,ymin,xmax,ymax :"),",")

print "Making a plot..."

w = PlotWidget(500,500,string.atof(ranges[0]),string.atof(ranges[1]), string.atof(ranges[2]),string.atof(ranges[3]))

# Turn user input into a Python function code = "def func(x): return " + line exec(code)

w.set_pymethod(func) w.plot()

f = open("plot.gif","w") w.save(f)

f.close()

posix.system("xv plot.gif &")

Other odds and ends

Adding native Python functions to a SWIG module

Sometimes it is desirable to add a native Python method to a SWIG wrapper file. Suppose you have the following Python/C function :

PyObject *spam_system(PyObject *self, PyObject *args) { char *command;

int sts;

if (!PyArg_ParseTuple(args,”s”,&command)) return NULL;

sts = system(command);

return Py_BuildValue(“i”,sts);

Version 1.1, June 24, 1997