adds "callback" and "extend" examples

This commit is contained in:
Robert Stone 2013-11-12 13:03:49 -08:00
commit 73e2de7538
14 changed files with 312 additions and 1 deletions

View file

@ -0,0 +1,20 @@
TOP = ../..
SWIG = $(TOP)/../preinst-swig
CXXSRCS = example.cxx
TARGET = example
INTERFACE = example.i
LIBS = -lm
check: build
$(MAKE) -f $(TOP)/Makefile perl5_run
build:
$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp
static:
$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static
clean:
$(MAKE) -f $(TOP)/Makefile perl5_clean

View file

@ -0,0 +1,4 @@
/* File : example.cxx */
#include "example.h"

View file

@ -0,0 +1,23 @@
/* File : example.h */
#include <cstdio>
#include <iostream>
class Callback {
public:
virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
virtual void run() { std::cout << "Callback::run()" << 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(); }
};

View file

@ -0,0 +1,17 @@
/* File : example.i */
%module(directors="1") example
%{
#include "example.h"
%}
%include "std_string.i"
/* turn on director wrapping Callback */
%feature("director") Callback;
/* Caller::setCallback(Callback *cb) gives ownership of the cb to the
* Caller object. The wrapper code should understand this. */
%apply SWIGTYPE *DISOWN { Callback *cb };
%include "example.h"

View file

@ -0,0 +1,20 @@
<html>
<head>
<title>SWIG:Examples:perl5:callback</title>
</head>
<body bgcolor="#ffffff">
<tt>SWIG/Examples/perl/callback/</tt>
<hr>
<H2>Implementing C++ callbacks in Perl</H2>
<p>
This example illustrates how to use directors to implement C++ callbacks.
</p>
<hr>
</body>
</html>

View file

@ -0,0 +1,40 @@
#!/usr/bin/perl
use strict;
use warnings;
use example;
{
package PerlCallback;
use base 'example::Callback';
sub run {
print "PerlCallback.run()\n";
}
}
print "Adding and calling a normal C++ callback\n";
print "----------------------------------------\n";
my $caller = example::Caller->new();
my $callback = example::Callback->new();
$caller->setCallback($callback);
$caller->call();
$caller->delCallback();
$callback = PerlCallback->new();
print "\n";
print "Adding and calling a Perl callback\n";
print "------------------------------------\n";
$caller->setCallback($callback);
$caller->call();
$caller->delCallback();
# Note that letting go of $callback will not attempt to destroy the
# object, ownership passed to $caller in the ->setCallback() call, and
# $callback was already destroyed in ->delCallback().
undef $callback;
print "\n";
print "perl exit\n";