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

SWIG Users Guide

SWIG and Tcl

230

 

 

 

Building an object oriented C interface

So far our tree example has been using the basic SWIG interface. With a little work in the interface file, we can improve the interface a little bit.

%module tree %{

#include "tree.h" %}

%include tree.h %{

/* Function to count up Nodes */

static int count_nodes(Node *n, Node *end) { if (n == end) return 0;

return 1+count_nodes(n->left,end)+count_nodes(n->right,end);

}

%}

// Attach some new methods to the Tree structure

%addmethods Tree {

void insert(char *key, char *value) { insert_tree(self,key,value);

}

char *search(char *key) {

return search_tree(self,key);

}

char *findnext(char *key) { return find_next(self,key);

}

int count() {

return count_nodes(self->head->right,self->z);

}

 

Tree();

// This is just another name for new_Tree

}

The %addmethods directive can be used to attach methods to existing structures and classes. In this case, we are attaching some methods to the Tree structure. Each of the methods are simply various C functions we have written for accessing trees. This type of interface file comes in particularly handy when using the Tcl object oriented interface. For example, we can rewrite our directory globber as follows :

proc build_dir_tree {tree pathname} {

set error [catch {set filelist [glob -nocomplain $pathname/*]}] if {$error == 0} {

foreach f $filelist {

if {[file isdirectory $f] == 1} {

$tree insert [file tail $f] $f # Note new calling method if {[file type $f] != "link"} {build_dir_tree $tree $f}

} {

$tree insert [file tail $f] $f

}

}

}

Version 1.1, June 24, 1997