From 315bd2da6eb0f48c05d00d204e350cc46782631b Mon Sep 17 00:00:00 2001 From: Gonzalo Garramuno Date: Mon, 7 May 2007 05:00:46 +0000 Subject: [PATCH] Added new iterator changes to std. This change does not break backwards compatability with python, so all works. The python stuff, however, will still not do all that ruby can now do. Updated manual to reflect the change and improve typemap documentation on the ruby side. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/trunk@9787 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Doc/Manual/Ruby.html | 4112 ++++++++++++++++++++++++++++++++++-- Lib/ruby/rubycontainer.swg | 110 +- Lib/ruby/rubyiterators.swg | 659 +++++- Lib/ruby/std_map.i | 45 +- Lib/ruby/std_set.i | 1 + Lib/std/std_map.i | 3 - Lib/std/std_set.i | 26 +- README | 3 +- 8 files changed, 4618 insertions(+), 341 deletions(-) diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index b48a9e08e..6cb756ce7 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -2,10 +2,13 @@ + + + SWIG and Ruby @@ -14,430 +17,698 @@ +

30 SWIG and Ruby

+
+
+

This chapter describes SWIG's support of Ruby.

+

30.1 Preliminaries

+

SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given the choice, you should use the latest stable version of Ruby. You should also determine if your system supports shared libraries and @@ -445,6 +716,7 @@ dynamic loading. SWIG will work with or without dynamic loading, but the compilation process will vary.

+

This chapter covers most SWIG features, but in less depth than is found in earlier chapters. At the very least, make sure you also read the "SWIG Basics" @@ -452,70 +724,87 @@ chapter. It is also assumed that the reader has a basic understanding of Ruby.

+

30.1.1 Running SWIG

+

To build a Ruby module, run SWIG using the -ruby option:

+
$ swig -ruby example.i
 
+
+

If building a C++ extension, add the -c++ option:

+
$ swig -c++ -ruby example.i
 
+
+

This creates a file example_wrap.c (example_wrap.cxx if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

+

30.1.2 Getting the right header files

+

In order to compile the wrapper code, the compiler needs the ruby.h header file. This file is usually contained in a directory such as

+
/usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h
/usr/local/lib/ruby/1.6/i686-linux/ruby.h
+
+

The exact location may vary on your machine, but the above location is typical. If you are not entirely sure where Ruby is installed, you can run Ruby to find out. For example:

+
$ ruby -e 'puts $:.join("\n")'
/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux
/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .
+
+

30.1.3 Compiling a dynamic module

+

Ruby extension modules are typically compiled into shared libraries that the interpreter loads dynamically at runtime. Since the exact commands for doing this vary from platform to platform, your best @@ -523,61 +812,81 @@ bet is to follow the steps described in the README.EXT file from the Ruby distribution:

+
    +
  1. +

    Create a file called extconf.rb that looks like the following:

    + +
    +
    require 'mkmf'
    create_makefile('example')
    +
    +
  2. +
  3. +

    Type the following to build the extension:

    + +
    +
    $ ruby extconf.rb
    $ make
    $ make install
    +
    +
  4. +
+

Of course, there is the problem that mkmf does not work correctly on all platforms, e.g, HPUX. If you need to add your own make rules to the file that extconf.rb produces, you can add this:

+
open("Makefile", "a") { |mf|
puts <<EOM
# Your make rules go here
EOM
}
+
+

to the end of the extconf.rb file. If for some reason you don't want to use the standard approach, you'll need to determine the correct compiler and linker flags for your build @@ -585,14 +894,17 @@ platform. For example, a typical sequence of commands for the Linux operating system would look something like this:

+
$ swig -ruby example.i
$ gcc -c example.c
$ gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux
$ gcc -shared example.o example_wrap.o -o example.so
+
+

For other platforms it may be necessary to compile with the -fPIC option to generate position-independent code. If in doubt, consult the manual pages for your compiler and linker to determine the correct set @@ -600,26 +912,32 @@ of options. You might also check the

+

30.1.4 Using your module

+

Ruby module names must be capitalized, but the convention for Ruby feature names is to use lowercase names. So, for example, the Etc extension module is imported by requiring the etc feature:

+
# The feature name begins with a lowercase letter...
require 'etc'

# ... but the module name begins with an uppercase letter
puts "Your login name: #{Etc.getlogin}"
+
+

To stay consistent with this practice, you should always specify a lowercase module name with SWIG's %module directive. SWIG will automatically correct the resulting Ruby module @@ -627,21 +945,26 @@ name for your extension. So for example, a SWIG interface file that begins with:

+
%module example
+
+

will result in an extension module using the feature name "example" and Ruby module name "Example".

+

30.1.5 Static linking

+

An alternative approach to dynamic linking is to rebuild the Ruby interpreter with your extension module added to it. In the past, this approach was sometimes necessary due to limitations in dynamic @@ -650,31 +973,38 @@ improved greatly over the last few years and you should not consider this approach unless there is really no other option.

+

The usual procedure for adding a new module to Ruby involves finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

+

+

30.1.6 Compilation of C++ extensions

+

On most machines, C++ extension modules should be linked using the C++ compiler. For example:

+
$ swig -c++ -ruby example.i
$ g++ -c example.cxx
$ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
$ g++ -shared example.o example_wrap.o -o example.so
+
+

If you've written an extconf.rb script to automatically generate a Makefile for your C++ extension module, keep in mind that (as of this writing) Ruby still @@ -687,17 +1017,21 @@ the C++ runtime libraries to the list of libraries linked into your extension, e.g.

+
require 'mkmf'
$libs = append_library($libs, "supc++")
create_makefile('example')
+
+

30.2 Building Ruby Extensions under Windows 95/NT

+

Building a SWIG extension to Ruby under Windows 95/NT is roughly similar to the process used with Unix. Normally, you will want to produce a DLL that can be loaded into the Ruby interpreter. For all @@ -706,14 +1040,17 @@ script) will work with Windows as well; you should be able to build your code into a DLL by typing:

+
C:\swigtest> ruby extconf.rb
C:\swigtest> nmake
C:\swigtest> nmake install
+
+

The remainder of this section covers the process of compiling SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within the Developer Studio IDE, instead of using the command line tools). In @@ -722,25 +1059,31 @@ distribution to the Ruby package, as you will need the Ruby header files.

+

+

30.2.1 Running SWIG from Developer Studio

+

If you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process roughly follows these steps :

+ +

Now, assuming all went well, SWIG will be automatically invoked when you build your project. Any changes made to the interface file will result in SWIG being automatically invoked to produce a new @@ -796,59 +1148,74 @@ Ruby and use the require command as normal. For example if you have this ruby file run.rb:

+
# file: run.rb
require 'Example'

# Call a c function
print "Foo = ", Example.Foo, "\n"
+
+

Ensure the dll just built is in your path or current directory, then run the Ruby script from the DOS/Command prompt:

+
C:\swigtest> ruby run.rb
Foo = 3.0
+
+

30.3 The Ruby-to-C/C++ Mapping

+

This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.

+

30.3.1 Modules

+

The SWIG %module directive specifies the name of the Ruby module. If you specify:

+
%module example
+
+

then everything is wrapped into a Ruby module named Example that is nested directly under the global module. You can specify a more deeply nested module by specifying the fully-qualified module name in quotes, e.g.

+
%module "foo::bar::spam"
+
+

An alternate method of specifying a nested module name is to use the -prefix option on the SWIG command line. The prefix that you specify with this @@ -857,63 +1224,79 @@ directive in your SWIG interface file. So for example, this declaration at the top of your SWIG interface file:
+

+
%module "foo::bar::spam"
+
+

will result in a nested module name of Foo::Bar::Spam, but you can achieve the same effect by specifying:
+

+
%module spam
+
+

and then running SWIG with the -prefix command line option:
+

+
$ swig -ruby -prefix "foo::bar::" example.i
+
+

Starting with SWIG 1.3.20, you can also choose to wrap everything into the global module by specifying the -globalmodule option on the SWIG command line, i.e.

+
$ swig -ruby -globalmodule example.i
+
+

Note that this does not relieve you of the requirement of specifying the SWIG module name with the %module directive (or the -module command-line option) as described earlier.

+

When choosing a module name, do not use the same name as a built-in Ruby command or standard module name, as the results may be unpredictable. Similarly, if you're using the -globalmodule @@ -922,203 +1305,255 @@ names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

+

30.3.2 Functions

+

Global functions are wrapped as Ruby module methods. For example, given the SWIG interface file example.i:

+
%module example

int fact(int n);
+
+

and C source file example.c:

+
int fact(int n) {
if (n == 0)
return 1;
return (n * fact(n-1));
}
+
+

SWIG will generate a method fact in the Example module that can be used like so:

+
$ irb
irb(main):001:0> require 'example'
true
irb(main):002:0> Example.fact(4)
24
+
+

30.3.3 Variable Linking

+

C/C++ global variables are wrapped as a pair of singleton methods for the module: one to get the value of the global variable and one to set it. For example, the following SWIG interface file declares two global variables:

+
// SWIG interface file with global variables
%module example
...
%inline %{
extern int variable1;
extern double Variable2;
%}
...
+
+

Now look at the Ruby interface:

+
$ irb
irb(main):001:0> require 'Example'
true
irb(main):002:0> Example.variable1 = 2
2
irb(main):003:0> Example.Variable2 = 4 * 10.3
41.2
irb(main):004:0> Example.Variable2
41.2
+
+

If you make an error in variable assignment, you will receive an error message. For example:

+
irb(main):005:0> Example.Variable2 = "hello"
TypeError: no implicit conversion to float from string
from (irb):5:in `Variable2='
from (irb):5
+
+

If a variable is declared as const, it is wrapped as a read-only variable. Attempts to modify its value will result in an error.

+

To make ordinary variables read-only, you can also use the %immutable directive. For example:

+
%immutable;
%inline %{
extern char *path;
%}
%mutable;
+
+

The %immutable directive stays in effect until it is explicitly disabled using %mutable.

+

30.3.4 Constants

+

C/C++ constants are wrapped as module constants initialized to the appropriate value. To create a constant, use #define or the %constant directive. For example:

+
#define PI 3.14159
#define VERSION "1.0"

%constant int FOO = 42;
%constant const char *path = "/usr/local";

const int BAR = 32;
+
+

Remember to use the :: operator in Ruby to get at these constant values, e.g.

+
$ irb
irb(main):001:0> require 'Example'
true
irb(main):002:0> Example::PI
3.14159
+
+

30.3.5 Pointers

+

"Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't explicitly declared in your SWIG interface file) are wrapped as data objects. So, for example, consider a SWIG interface file containing only the declarations:

+
Foo *get_foo();
void set_foo(Foo *foo);
+
+

For this case, the get_foo() method returns an instance of an internally generated Ruby class:

+
irb(main):001:0> foo = Example::get_foo()
#<SWIG::TYPE_p_Foo:0x402b1654>
+
+

A NULL pointer is always represented by the Ruby nil object.

+

30.3.6 Structures

+

C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. "getters" and "setters") for all of the struct members. For example, this struct declaration:

+
struct Vector {
double x, y;
};
+
+

gets wrapped as a Vector class, with Ruby instance methods x, x=, y and y=. These methods can be used to access structure data from Ruby as follows:

+
$ irb
irb(main):001:0> require 'Example'
true
irb(main):002:0> f = Example::Vector.new
#<Example::Vector:0x4020b268>
irb(main):003:0> f.x = 10
nil
irb(main):004:0> f.x
10.0
+
+

Similar access is provided for unions and the public data members of C++ classes.

+

const members of a structure are read-only. Data members can also be forced to be read-only using the %immutable directive (in C++, private may also be used). For example:

+
struct Foo {
...
%immutable;
int x; /* Read-only members */
char *name;
%mutable;
...
};
+
+

When char * members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not SWIG is run @@ -1128,27 +1563,34 @@ this is not the behavior you want, you will have to use a typemap (described shortly).

+

Array members are normally wrapped as read-only. For example, this code:

+
struct Foo {
int x[50];
};
+
+

produces a single accessor function like this:

+
int *Foo_x_get(Foo *self) {
return self->x;
};
+
+

If you want to set an array member, you will need to supply a "memberin" typemap described in the section on typemaps. As a special case, SWIG does generate code to set array members of type @@ -1156,30 +1598,38 @@ As a special case, SWIG does generate code to set array members of type structure).

+

When structure members are wrapped, they are handled as pointers. For example,

+
struct Foo {
...
};

struct Bar {
Foo f;
};
+
+

generates accessor functions such as this:

+
Foo *Bar_f_get(Bar *b) {
return &b->f;
}

void Bar_f_set(Bar *b, Foo *val) {
b->f = *val;
}
+
+

30.3.7 C++ classes

+

Like structs, C++ classes are wrapped by creating a new Ruby class of the same name with accessor methods for the public class member data. Additionally, public member functions for the class are @@ -1188,86 +1638,109 @@ are wrapped as Ruby singleton methods. So, given the C++ class declaration:

+
class List {
public:
List();
~List();
int search(char *item);
void insert(char *item);
void remove(char *item);
char *get(int n);
int length;
static void print(List *l);
};
+
+

SWIG would create a List class with:

+ +

In Ruby, these functions are used as follows:

+
require 'Example'

l = Example::List.new

l.insert("Ale")
l.insert("Stout")
l.insert("Lager")
Example.print(l)
l.length()
----- produces the following output
Lager
Stout
Ale
3
+
+

30.3.8 C++ Inheritance

+

The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have classes like this:

+
class Parent {
...
};

class Child : public Parent {
...
};
+
+

those classes are wrapped into a hierarchy of Ruby classes that reflect the same inheritance structure. All of the usual Ruby utility methods work normally:

+
irb(main):001:0> c = Child.new
#<Bar:0x4016efd4>
irb(main):002:0> c.instance_of? Child
true
irb(main):003:0> b.instance_of? Parent
false
irb(main):004:0> b.is_a? Child
true
irb(main):005:0> b.is_a? Parent
true
irb(main):006:0> Child < Parent
true
irb(main):007:0> Child > Parent
false
+
+

Furthermore, if you have a function like this:

+
void spam(Parent *f);
+
+

then the function spam() accepts Parent* or a pointer to any class derived from Parent.

+

Until recently, the Ruby module for SWIG didn't support multiple inheritance, and this is still the default behavior. This doesn't mean that you can't wrap C++ classes which inherit from @@ -1277,13 +1750,16 @@ additional base classes are ignored. As an example, consider a SWIG interface file with a declaration like this:

+
class Derived : public Base1, public Base2
{
...
};
+
+

For this case, the resulting Ruby class (Derived) will only consider Base1 as its superclass. It won't inherit any of Base2's member functions or @@ -1293,13 +1769,16 @@ relationship would fail). When SWIG processes this interface file, you'll see a warning message like:

+
example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.
Multiple inheritance is not supported in Ruby.
+
+

Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited support for multiple inheritance. Because the approach for dealing with multiple inheritance introduces some limitations, this is @@ -1307,24 +1786,30 @@ an optional feature that you can activate with the -minherit command-line option:

+
$ swig -c++ -ruby -minherit example.i
+
+

Using our previous example, if your SWIG interface file contains a declaration like this:

+
class Derived : public Base1, public Base2
{
...
};
+
+

and you run SWIG with the -minherit command-line option, then you will end up with a Ruby class Derived that appears to "inherit" the member data and functions from both Base1 @@ -1336,13 +1821,16 @@ modules that the actual instance methods for the classes are defined, i.e.

+
class Base1
module Impl
# Define Base1 methods here
end
include Impl
end

class Base2
module Impl
# Define Base2 methods here
end
include Impl
end

class Derived
module Impl
include Base1::Impl
include Base2::Impl
# Define Derived methods here
end
include Impl
end
+
+

Observe that after the nested Impl module for a class is defined, it is mixed-in to the class itself. Also observe that the Derived::Impl module first @@ -1350,18 +1838,22 @@ mixes-in its base classes' Impl modules, thus "inheriting" all of their behavior.

+

The primary drawback is that, unlike the default mode of operation, neither Base1 nor Base2 is a true superclass of Derived anymore:

+
obj = Derived.new
obj.is_a? Base1 # this will return false...
obj.is_a? Base2 # ... and so will this
+
+

In most cases, this is not a serious problem since objects of type Derived will otherwise behave as though they inherit from both Base1 and Base2 @@ -1369,105 +1861,134 @@ inherit from both Base1 and Base2 Typing").

+

30.3.9 C++ Overloaded Functions

+

C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

+
void foo(int);
void foo(char *c);
+
+

You can use them in Ruby in a straightforward manner:

+
irb(main):001:0> foo(3) # foo(int)
irb(main):002:0> foo("Hello") # foo(char *c)
+
+

Similarly, if you have a class like this,

+
class Foo {
public:
Foo();
Foo(const Foo &);
...
};
+
+

you can write Ruby code like this:

+
irb(main):001:0> f = Foo.new # Create a Foo
irb(main):002:0> g = Foo.new(f) # Copy f
+
+

Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:

+
void spam(int);
void spam(short);
+
+

or

+
void foo(Bar *b);
void foo(Bar &b);
+
+

If declarations such as these appear, you will get a warning message like this:

+
example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
at example.i:11.
+
+

To fix this, you either need to ignore or rename one of the methods. For example:

+
%rename(spam_short) spam(short);
...
void spam(int);
void spam(short); // Accessed as spam_short
+
+

or

+
%ignore spam(short);
...
void spam(int);
void spam(short); // Ignored
+
+

SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in @@ -1475,30 +1996,37 @@ the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

+

Please refer to the "SWIG and C++" chapter for more information about overloading.

+

30.3.10 C++ Operators

+

For the most part, overloaded operators are handled automatically by SWIG and do not require any special treatment on your part. So if your class declares an overloaded addition operator, e.g.

+
class Complex {
...
Complex operator+(Complex &);
...
};
+
+

the resulting Ruby class will also support the addition (+) method correctly.

+

For cases where SWIG's built-in support is not sufficient, C++ operators can be wrapped using the %rename directive (available on SWIG 1.3.10 and later releases). All you need @@ -1506,67 +2034,84 @@ to do is give the operator the name of a valid Ruby identifier. For example:

+
%rename(add_complex) operator+(Complex &, Complex &);
...
Complex operator+(Complex &, Complex &);
+
+

Now, in Ruby, you can do this:

+
a = Example::Complex.new(2, 3)
b = Example::Complex.new(4, -1)
c = Example.add_complex(a, b)
+
+

More details about wrapping C++ operators into Ruby operators is discussed in the section on operator overloading.

+

30.3.11 C++ namespaces

+

SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

+
%module example

namespace foo {
int fact(int n);
struct Vector {
double x,y,z;
};
};
+
+

it works in Ruby as follows:

+
irb(main):001:0> require 'example'
true
irb(main):002:0> Example.fact(3)
6
irb(main):003:0> v = Example::Vector.new
#<Example::Vector:0x4016f4d4>
irb(main):004:0> v.x = 3.4
3.4
irb(main):004:0> v.y
0.0
+
+

If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

+
%rename(Bar_spam) Bar::spam;

namespace Foo {
int spam();
}

namespace Bar {
int spam();
}
+
+

If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace @@ -1575,37 +2120,46 @@ program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

+

30.3.12 C++ templates

+

C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

+
%module example

%{
#include "pair.h"
%}

template<class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair();
pair(const T1&, const T2&);
~pair();
};

%template(Pairii) pair<int,int>;
+
+

In Ruby:

+
irb(main):001:0> require 'example'
true
irb(main):002:0> p = Example::Pairii.new(3, 4)
#<Example:Pairii:0x4016f4df>
irb(main):003:0> p.first
3
irb(main):004:0> p.second
4
+
+

30.3.12.1 C++ Standard Template Library (STL)

+

On a related note, the standard SWIG library contains a number of modules that provide typemaps for standard C++ library classes (such as std::pair, std::string @@ -1617,40 +2171,50 @@ of standard C++ templates. For example, suppose the C++ library you're wrapping has a function that expects a vector of floats:

+
%module example

float sum(const std::vector<float>& values);
+
+

Rather than go through the hassle of writing an "in" typemap to convert an array of Ruby numbers into a std::vector<float>, you can just use the std_vector.i module from the standard SWIG library:

+
%module example

%include std_vector.i
float sum(const std::vector<float>& values);
+
+

Ruby's STL wrappings provide additional methods to make them behave more similarly to Ruby's native classes.

+

Thus, you can do, for example:

+
v = IntVector.new
v << 2

v << 3
v << 4
v.each { |x| puts x }

=> 2

3
4
v.delete_if { |x| x == 3 }
=> [2,4]
+
+

The SWIG Ruby module provides also the ability for all the STL containers to carry around Ruby native objects (Fixnum, Classes, etc) making them act almost like Ruby's own Array, Hash, etc.   To @@ -1659,207 +2223,497 @@ that, you need to define a container that contains a swig::GC_VALUE, like:

+
%module nativevector
+
+ %{
+ std::vector< swig::GC_VALUE > NativeVector;
+ %}
+
+ %template(NativeVector) std::vector< swig::GC_VALUE >;
+
+
+

This vector can then contain any Ruby object, making them almost identical to Ruby's own Array class.

+
require 'nativevector'
+ include NativeVector
+
+ v = NativeVector.new
+ v << 1
+ v << [1,2]
+ v << 'hello'
+
+ class A; end
+
+ v << A.new
+
+ puts v
+ => [1, [1,2], 'hello', #<A:0x245325>]
+
+

Obviously, there is a lot more to template wrapping than shown in these examples. More details can be found in the SWIG and C++ chapter.

-

30.3.12.1.2 C++ + + + +

30.3.12.1.2 +C++ STL Functors

+ + +

Some containers in the STL allow you to modify their default behavior by using so called functors or function objects.  Functors are often just a very simple struct with operator() redefined or an actual C/C++ function.  This allows you, for example, to always keep the sort order of a STL container to your liking.

-

The Ruby STL mappings allows you to modify those containers that -support functors using Ruby procs or methods, instead.  Currently, -this includes std::set, set::map, std::multiset and std::multimap.

-

The functors in swig are called swig::UnaryFunction and swig::BinaryFunction.
-For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate and swig::BinaryPredicate are provided.

+ + + +

The Ruby STL mappings allows you to modify those containers +that +support functors using Ruby procs or methods, instead. + Currently, +this includes std::set, +set::map, +std::multiset +and std::multimap.

+ + + +

The functors in swig are called swig::UnaryFunction +and swig::BinaryFunction.
+ + + +For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate +and swig::BinaryPredicate +are provided.

+ + +

As an example, if given this swig file:

-
%module intset;
+ + + +
%module +intset;
+ + +
+ + + %include std_set.i
+ + +
-%typemap(IntSet)  std::set< int, swig::BinaryPredicate >;
-

You can then use the set from Ruby with or without a proc object as a predicate:

-
require 'intset'
+ + + +%typemap(IntSet)  std::set< int, swig::BinaryPredicate +>;
+ + + +

You can then use the set from Ruby with or without a proc +object as a predicate:

+ + + +
require +'intset'
+ + + include Intset
+ + +
+ + + # Default sorting behavior defined in C++
+ + + a = IntSet.new
+ + + a << 1
+ + + a << 2
+ + + a << 3
+ + + a
-=>  [1,2,3]
+ + + +=> + [1,2,3]
+ + +
+ + + # Custom sorting behavior defined by a Ruby proc -
b = IntSet.new( proc { |a,b| a > b } )
+
b = IntSet.new( proc { +|a,b| a > b } )
+ + + b << 1
+ + + b << 2
+ + + b << 3
+ + + b
-=>  [3,2,1]
+ + + +=> + [3,2,1]
+ + +
+ +

30.3.12.1.3 +C++ STL Iterators

+ + + +

The STL is well known by the use of iterators.  There +are a number of iterators possible with different properties, but in +general there are two main categories: const iterators and non-const +iterators.  The const iterators can access and not modify the +values they point at, while the non-const iterators can both read and +modify the values.

+ + + +

The Ruby STL wrappings support both type of iterators by using +a proxy class in-between.  This proxy class is swig::Iterator or +swig::ConstIterator.  They are both template +classes that need to be initialized with the actual iterator for the +container you are wrapping and often times with the beginning and +ending points of the iteration range.

+ + + +

The SWIG STL library already provides typemaps to all the +standard containers to do this wrapping automatically for you, but if +you have your own STL-like class, you will need to write your own +typemap for them.

+ + + +

The iterators support the next() and previous() functions +to both increment/decrement the iterator and return the current (old) +value, and the functions decr() +and incr() to +just change the iterator without returning anything.  The +value of the iterator can be accessed with value(). +  For non-const iterators, a set() function +is also provided which allows you to change the value pointed by the +iterator. 

+ + + +

Thus, given say a vector class of doubles defined as:

+ + + +
%module doublevector
+ + + +
+ + + +%include std_vector.i

+ + + +
+ + + +%template(DoubleVector) std::vector<double>;
+ + + +

its iterator can then be used from Ruby like:

+ + + +
require +'doublevector'
+ + + +include Doublevector
+ + + +v = DoubleVector.new
+ + + +v << 1
+ + + +v << 2
+ + + +v << 3
+ + + +i = v.begin
+ + + +e = v.end
+ + + +while i != e
+ + + +  val = i.value
+ + + +  val += 2
+ + + +  i.set( val )
+ + + +  i.incr
+ + + +end
+ + +i
+ + +>> [3, 4, 5 ]
+ + + +
+ + +

30.3.13 C++ Smart Pointers

+

In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:

+
template<class T> class SmartPtr {
...
T *operator->();
...
}
+
+

Then, if you have a class like this,

+
class Foo {
public:
int x;
int bar();
};
+
+

A smart pointer would be used in C++ as follows:

+
SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
...
p->x = 3; // Foo::x
int y = p->bar(); // Foo::bar
+
+

To wrap this in Ruby, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using %template if necessary. For example:

+
%module example
...
%template(SmartPtrFoo) SmartPtr<Foo>;
...
+
+

Now, in Ruby, everything should just "work":

+
irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow
#<Example::SmartPtrFoo:0x4016f4df>
irb(main):002:0> p.x = 3 # Foo::x
3
irb(main):003:0> p.bar() # Foo::bar
+
+

If you ever need to access the underlying pointer returned by operator->() itself, simply use the __deref__() method. For example:

+
irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
+
+

30.3.14 Cross-Language Polymorphism

+

SWIG's Ruby module supports cross-language polymorphism (a.k.a. the "directors" feature) similar to that for SWIG's Python module. Rather than duplicate the information presented in the Python chapter, this @@ -1867,10 +2721,12 @@ section just notes the differences that you need to be aware of when using this feature with Ruby.

+

30.3.14.1 Exception Unrolling

+

Whenever a C++ director class routes one of its virtual member function calls to a Ruby instance method, there's always the possibility that an exception will be raised in the Ruby code. By @@ -1881,52 +2737,65 @@ directive to indicate what action should be taken when a Ruby exception is raised. The following code should suffice in most cases:

+
%feature("director:except") {
throw Swig::DirectorMethodException($error);
}
+
+

When this feature is activated, the call to the Ruby instance method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

+

30.4 Naming

+

Ruby has several common naming conventions. Constants are generally in upper case, module and class names are in camel case and methods are in lower case with underscores. For example:

+
    +
  • MATH::PI is a constant name
  • +
  • MyClass is a class name
  • +
  • my_method is a method name
  • +
+
+

Prior to version 1.3.28, SWIG did not support these Ruby conventions. The only modifications it made to names was to capitalize the first letter of constants (which includes module and class names).

+

SWIG 1.3.28 introduces the new -autorename command line parameter. When this parameter is specified, SWIG will automatically change @@ -1934,27 +2803,33 @@ constant, class and method names to conform with the standard Ruby naming conventions. For example:

+
$ swig -ruby -autorename example.i
 
+
+

To disable renaming use the -noautorename command line option.

+

Since this change significantly changes the wrapper code generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

+

30.4.1 Defining Aliases

+

It's a fairly common practice in the Ruby built-ins and standard library to provide aliases for method names. For example, Array#size is an alias for Array#length. If you would like @@ -1964,37 +2839,46 @@ add a new method of the aliased name that calls the original function. For example:

+
class MyArray {
public:
// Construct an empty array
MyArray();

// Return the size of this array
size_t length() const;
};

%extend MyArray {
// MyArray#size is an alias for MyArray#length
size_t size() const {
return $self->length();
}
}
+
+

A better solution is to use the %alias directive (unique to SWIG's Ruby module). The previous example could then be rewritten as:

+
// MyArray#size is an alias for MyArray#length
%alias MyArray::length "size";

class MyArray {
public:
// Construct an empty array
MyArray();

// Return the size of this array
size_t length() const;
};

+
+

Multiple aliases can be associated with a method by providing a comma-separated list of aliases to the %alias directive, e.g.

+
%alias MyArray::length "amount,quantity,size";
+
+

From an end-user's standpoint, there's no functional difference between these two approaches; i.e. they should get the same result from calling either MyArray#size or MyArray#length. @@ -2004,6 +2888,7 @@ associated with added methods like our MyArray::size() example.

+

Note that the %alias directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter @@ -2011,10 +2896,12 @@ on "Customization Features") for more details).

+

30.4.2 Predicate Methods

+

Ruby methods that return a boolean value and end in a question mark are known as predicate methods. Examples of predicate methods in @@ -2026,6 +2913,7 @@ with Ruby conventions, methods that return boolean values should be marked as predicate methods.

+

One cumbersome solution to this problem is to rename the method (using SWIG's %rename directive) and provide a custom typemap that converts the function's actual return @@ -2033,44 +2921,55 @@ type to Ruby's true or false. For example:

+
%rename("is_it_safe?") is_it_safe();

%typemap(out) int is_it_safe
"$result = ($1 != 0) ? Qtrue : Qfalse;";

int is_it_safe();

+
+

A better solution is to use the %predicate directive (unique to SWIG's Ruby module) to designate a method as a predicate method. For the previous example, this would look like:

+
%predicate is_it_safe();

int is_it_safe();

+
+

This method would be invoked from Ruby code like this:

+
irb(main):001:0> Example::is_it_safe?
true

+
+

The %predicate directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

+

30.4.3 Bang Methods

+

Ruby methods that modify an object in-place and end in an exclamation mark are known as bang methods. An example of a bang method is Array#sort! which changes the ordering of @@ -2080,224 +2979,283 @@ modifying the original array. For consistency with Ruby conventions, methods that modify objects in place should be marked as bang methods.

+

Bang methods can be marked using the %bang directive which is unique to the Ruby module and was introduced in SWIG 1.3.28. For example:

+
%bang sort!(arr);

int sort(int arr[]);
+
+

This method would be invoked from Ruby code like this:

+
irb(main):001:0> Example::sort!(arr)
+
+

The %bang directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

+

30.4.4 Getters and Setters

+

Often times a C++ library will expose properties through getter and setter methods. For example:

+
class Foo {
Foo() {}

int getValue() { return value_; }

void setValue(int value) { value_ = value; }

private:
int value_;
};
+
+

By default, SWIG will expose these methods to Ruby as get_value and set_value. However, it more natural for these methods to be exposed in Ruby as value and value=. That allows the methods to be used like this:

+
irb(main):001:0> foo = Foo.new()
irb(main):002:0> foo.value = 5
irb(main):003:0> puts foo.value
+
+

This can be done by using the %rename directive:

+
%rename("value") Foo::getValue();
%rename("value=") Foo::setValue(int value);
+
+

 

+

30.5 Input and output parameters

+

A common problem in some C programs is handling parameters passed as simple pointers. For example:

+
void add(int x, int y, int *result) {
*result = x + y;
}
or
int sub(int *x, int *y) {
return *x-*y;
}
+
+

The easiest way to handle these situations is to use the typemaps.i file. For example:

+
%module Example
%include "typemaps.i"

void add(int, int, int *OUTPUT);
int sub(int *INPUT, int *INPUT);
+
+

In Ruby, this allows you to pass simple values. For example:

+
a = Example.add(3,4)
puts a
7
b = Example.sub(7,4)
puts b
3
+
+

Notice how the INPUT parameters allow integer values to be passed instead of pointers and how the OUTPUT parameter creates a return result.

+

If you don't want to use the names INPUT or OUTPUT, use the %apply directive. For example:

+
%module Example
%include "typemaps.i"

%apply int *OUTPUT { int *result };
%apply int *INPUT { int *x, int *y};

void add(int x, int y, int *result);
int sub(int *x, int *y);
+
+

If a function mutates one of its parameters like this,

+
void negate(int *x) {
*x = -(*x);
}
+
+

you can use INOUT like this:

+
%include "typemaps.i"
...
void negate(int *INOUT);
+
+

In Ruby, a mutated parameter shows up as a return value. For example:

+
a = Example.negate(3)
print a
-3

+
+

The most common use of these special typemap rules is to handle functions that return more than one value. For example, sometimes a function returns a result as well as a special error code:

+
/* send message, return number of bytes sent, success code, and error_code */
int send_message(char *text, int *success, int *error_code);
+
+

To wrap such a function, simply use the OUTPUT rule above. For example:

+
%module example
%include "typemaps.i"
...
int send_message(char *, int *OUTPUT, int *OUTPUT);
+
+

When used in Ruby, the function will return an array of multiple values.

+
bytes, success, error_code = send_message("Hello World")
if not success
print "error #{error_code} : in send_message"
else
print "Sent", bytes
end
+
+

Another way to access multiple return values is to use the %apply rule. In the following example, the parameters rows and columns are related to SWIG as OUTPUT values through the use of %apply

+
%module Example
%include "typemaps.i"
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, int*columns);
+
+

In Ruby:

+
r, c = Example.get_dimensions(m)
+
+

30.6 Exception handling

+

30.6.1 Using the %exception directive

+

The SWIG %exception directive can be used to define a user-definable exception handler that can convert C/C++ errors into Ruby exceptions. The chapter on Customization @@ -2305,25 +3263,31 @@ Features contains more details, but suppose you have a C++ class like the following :

+
class DoubleArray {
private:
int n;
double *ptr;
public:
// Create a new array of fixed size
DoubleArray(int size) {
ptr = new double[size];
n = size;
}

// Destroy an array
~DoubleArray() {
delete ptr;
}

// Return the length of the array
int length() {
return n;
}

// Get an array item and perform bounds checking.
double getitem(int i) {
if ((i >= 0) && (i < n))
return ptr[i];
else
throw RangeError();
}

// Set an array item and perform bounds checking.
void setitem(int i, double val) {
if ((i >= 0) && (i < n))
ptr[i] = val;
else {
throw RangeError();
}
}
};
+
+

Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the Ruby extension by writing the following in an interface file:

+
%exception {
try {
$action
}
catch (const RangeError&) {
static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
rb_raise(cpperror, "Range error.");
}
}

class DoubleArray {
...
};
+
+

The exception handling code is inserted directly into generated wrapper functions. When an exception handler is defined, errors can be caught and used to gracefully raise a Ruby exception @@ -2331,33 +3295,40 @@ instead of forcing the entire program to terminate with an uncaught error.

+

As shown, the exception handling code will be added to every wrapper function. Because this is somewhat inefficient, you might consider refining the exception handler to only apply to specific methods like this:

+
%exception getitem {
try {
$action
}
catch (const RangeError&) {
static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
rb_raise(cpperror, "Range error in getitem.");
}
}

%exception setitem {
try {
$action
}
catch (const RangeError&) {
static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
rb_raise(cpperror, "Range error in setitem.");
}
}
+
+

In this case, the exception handler is only attached to methods and functions named getitem and setitem.

+

Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling. See the chapter on Customization Features for more examples.

+

30.6.2 Handling Ruby Blocks

+

One of the highlights of Ruby and most of its standard library is the use of blocks, which allow the easy creation of continuations and @@ -2365,301 +3336,604 @@ other niceties.  Blocks in ruby are also often used to simplify the passing of many arguments to a class.

+

In order to make your class constructor support blocks, you can take advantage of the %exception directive, which will get run after the C++ class' constructor was called. 

+

For example, this yields the class over after its construction:
+

+
class Window
{
public:
Window(int x, int y, int w, int h);
// .... other methods here ....
};

// Add support for yielding self in the Class' constructor.
%exception Window::Window {
$action
if (rb_block_given_p()) {
rb_yield(self);
}
}
+
+

Then, in ruby, it can be used like:

+
Window.new(0,0,360,480) { |w|
+     w.color = Fltk::RED
+     w.border = false
+ }
+

+

For other methods, you can usually use a dummy parameter with a special in typemap, like:

+
//
+ // original function was:
+ //
+ // void func(int x);
+
+ %typemap(in,numinputs=0) int RUBY_YIELD_SELF {
+      if ( !rb_block_given_p() )
+             rb_raise("No block given");
+      return rb_yield(self);
+ }
+
+ %extend {
+         void func(int x, int RUBY_YIELD_SELF );
+ }
+

For more information on typemaps, see Typemaps.

+
+

30.6.3 Raising exceptions

+

There are three ways to raise exceptions from C++ code to Ruby.

+

The first way is to use SWIG_exception(int code, const char *msg). The following table shows the mappings from SWIG error codes to Ruby exceptions:

- + +
+
+ + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + + - + + + + + + + + + - + + - + + + + +
SWIG_MemoryError + + +
SWIG_MemoryError
-
rb_eNoMemError + + +
rb_eNoMemError
+ + + +
SWIG_IOError + + +
SWIG_IOError
-
rb_eIOError + + +
rb_eIOError
+ + + +
SWIG_RuntimeError + + +
SWIG_RuntimeError
-
rb_eRuntimeError + + +
rb_eRuntimeError
+ + + +
SWIG_IndexError + + +
SWIG_IndexError
-
rb_eIndexError + + +
rb_eIndexError
+ + + +
SWIG_TypeError + + +
SWIG_TypeError
-
rb_eTypeError + + +
rb_eTypeError
+ + + +
SWIG_DivisionByZero + + +
SWIG_DivisionByZero
-
rb_eZeroDivError + + +
rb_eZeroDivError
+ + + +
SWIG_OverflowError + + +
SWIG_OverflowError
-
rb_eRangeError + + +
rb_eRangeError
+ + + +
SWIG_SyntaxError + + +
SWIG_SyntaxError
-
rb_eSyntaxError + + +
rb_eSyntaxError
+ + + +
SWIG_ValueError + + +
SWIG_ValueError
-
rb_eArgError + + +
rb_eArgError
+ + + +
SWIG_SystemError + + +
SWIG_SystemError
-
rb_eFatal + + +
rb_eFatal
+ + + +
SWIG_AttributeError + + +
SWIG_AttributeError
-
rb_eRuntimeError + + +
rb_eRuntimeError
+ + + +
SWIG_NullReferenceError + + +
SWIG_NullReferenceError
-
rb_eNullReferenceError* + + +
rb_eNullReferenceError*
+ + + +
SWIG_ObjectPreviouslyDeletedError + + +
SWIG_ObjectPreviouslyDeletedError
-
rb_eObjectPreviouslyDeleted* + + +
rb_eObjectPreviouslyDeleted*
+ + + +
SWIG_UnknownError + + +
SWIG_UnknownError
-
rb_eRuntimeError + + +
rb_eRuntimeError
+ + + +
* These error classes are created by -SWIG and are not built-in Ruby exception classes + + +
* These error classes are created by +SWIG and are not built-in Ruby exception classes
+ + + +
+ +
+ + +

The second way to raise errors is to use SWIG_Raise(obj, type, desc). Obj is a C++ instance of an exception class, type is a string @@ -2667,12 +3941,14 @@ specifying the type of exception (for example, "MyError") and desc is the SWIG description of the exception class. For example:

+
%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);
+

This is useful when you want to pass the current exception object directly to Ruby, particularly when the object is an instance of class @@ -2680,6 +3956,7 @@ marked as an %exceptionclass (see the next section for more information).

+

Last, you can raise an exception by directly calling Ruby's C api. This is done by invoking the rb_raise() function. The first argument passed to rb_raise() @@ -2687,10 +3964,12 @@ is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

+

30.6.4 Exception classes

+

Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass directive, which is used to identify C++ classes that are used as exceptions. Classes that are marked with the %exceptionclass @@ -2699,32 +3978,41 @@ This allows C++ exceptions to be directly mapped to Ruby exceptions, providing for a more natural integration between C++ code and Ruby code.

+
	%exceptionclass CustomError;

%inline %{
class CustomError { };

class Foo {
public:
void test() { throw CustomError; }
};
}
+
+

From Ruby you can now call this method like this:

+
foo = Foo.new
begin
foo.test()
rescue CustomError => e
puts "Caught custom error"
end
+
+

For another example look at swig/Examples/ruby/exception_class.
+

+

30.7 Typemaps

+

This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the @@ -2733,28 +4021,96 @@ chapter. 

+

Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

+

30.7.1 What is a typemap?

+

A typemap is nothing more than a code generation rule that is -attached to a specific C datatype. For example, to convert integers +attached to a specific C datatype. The general form of this declaration +is as follows ( parts enclosed in [...] are optional +):    

+ + + +
%typemap( method [, modifiers...] ) typelist +code;
+ + + +

method is a simply a name that specifies +what kind of typemap is being defined. It is usually a name like "in", +"out", or "argout" (or its +director variations). The purpose of these methods is described later.

+ + + +

modifiers is an optional comma separated +list of +name="value" values. These are sometimes to attach extra +information to a typemap and is often target-language dependent.

+ + + +

typelist is a list of the C++ type +patterns that the typemap will match. The general form of this list is +as follows:

+ + + +
+
typelist : typepattern [, typepattern, typepattern, ... ] ;

typepattern : type [ (parms) ]
| type name [ (parms) ]
| ( typelist ) [ (parms) ]
+ + + +
+ + + +

Each type pattern is either a simple type, a simple type and +argument name, or a list of types in the case of multi-argument +typemaps. In addition, each type pattern can be parameterized with a +list of temporary variables (parms). The purpose of these variables +will be explained shortly.

+ + + +

code specifies the C code used in the +typemap. It can take any one of the following forms:

+ + + +
+
code : { ... }
| " ... "
| %{ ... %}
+ + + +
+ + + +

For example, to convert integers from Ruby to C, you might define a typemap like this:

+
%module example

%typemap(in) int {
$1 = (int) NUM2INT($input);
printf("Received an integer : %d\n",$1);
}

%inline %{
extern int fact(int n);
%}
+
+

Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is @@ -2765,43 +4121,54 @@ variable is placeholder for a local variable of type int. The $input variable is the input Ruby object.

+

When this example is compiled into a Ruby module, the following sample code:

+
require 'example'

puts Example.fact(6)
+
+

prints the result:

+
Received an integer : 6
720
+
+

In this example, the typemap is applied to all occurrences of the int datatype. You can refine this by supplying an optional parameter name. For example:

+
%module example

%typemap(in) int n {
$1 = (int) NUM2INT($input);
printf("n = %d\n",$1);
}

%inline %{
extern int fact(int n);
%}
+
+

In this case, the typemap code is only attached to arguments that exactly match "int n".

+

The application of a typemap to specific datatypes and argument names involves more than simple text-matching--typemaps are fully integrated into the SWIG type-system. When you define a typemap @@ -2811,180 +4178,1544 @@ addition, the typemap system follows typedef declarations. For example:

+
%typemap(in) int n {
$1 = (int) NUM2INT($input);
printf("n = %d\n",$1);
}

typedef int Integer;
extern int fact(Integer n); // Above typemap is applied
+
+

However, the matching of typedef only occurs in one direction. If you defined a typemap for Integer, it is not applied to arguments of type int.

+

Typemaps can also be defined for groups of consecutive arguments. For example:

+
%typemap(in) (char *str, int len) {
$1 = STR2CSTR($input);
$2 = (int) RSTRING($input)->len;
};

int count(char c, char *str, int len);
+
+

When a multi-argument typemap is defined, the arguments are always handled as a single Ruby object. This allows the function count to be used as follows (notice how the length parameter is omitted):

+
puts Example.count('o','Hello World')
2
+
-

30.7.2 Ruby -typemaps

+ +

30.7.2 +Typemap scope

-

The previous section illustrated an "in" typemap for -converting Ruby objects to C. A variety of different typemap methods -are defined by the Ruby module. For example, to convert a C integer -back into a Ruby object, you might define an "out" typemap like this:

+ +

Once defined, a typemap remains in effect for all of the +declarations that follow. A typemap may be redefined for different +sections of an input file. For example:

+
-
%typemap(out) int {
$result = INT2NUM($1);
}
+
// typemap1
%typemap(in) int {
...
}

int fact(int); // typemap1
int gcd(int x, int y); // typemap1

// typemap2
%typemap(in) int {
...
}

int isprime(int); // typemap2
+
-

The following list details all of the typemap methods that + +

One exception to the typemap scoping rules pertains to the +%extend declaration. %extend is used +to attach new declarations to a class or structure definition. Because +of this, all of the declarations in an %extend +block are subject to the typemap rules that are in effect at the point +where the class itself is defined. For example:

+ + + +
+
class Foo {
...
};

%typemap(in) int {
...
}

%extend Foo {
int blah(int x); // typemap has no effect. Declaration is attached to Foo which
// appears before the %typemap declaration.
};
+ + + +
+ + + +

30.7.3 +Copying +a typemap

+ + + +

A typemap is copied by using assignment. For example:

+ + + +
+
%typemap(in) Integer = int;
+ + + +
+ + + +

or this:

+ + + +
+
%typemap(in) Integer, Number, int32_t = int;
+ + + +
+ + + +

Types are often managed by a collection of different +typemaps. For example:

+ + + +
+
%typemap(in) int { ... }
%typemap(out) int { ... }
%typemap(varin) int { ... }
%typemap(varout) int { ... }
+ + + +
+ + + +

To copy all of these typemaps to a new type, use %apply. +For example:

+ + + +
+
%apply int { Integer }; // Copy all int typemaps to Integer
%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
+ + + +
+ + + +

The patterns for %apply follow the same +rules as for +%typemap. For example:

+ + + +
+
%apply int *output { Integer *output }; // Typemap with name
%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
+ + + +
+ + + +

30.7.4 +Deleting a typemap

+ + + +

A typemap can be deleted by simply defining no code. For +example:

+ + + +
+
%typemap(in) int; // Clears typemap for int
%typemap(in) int, long, short; // Clears typemap for int, long, short
%typemap(in) int *output;
+ + + +
+ + + +

The %clear directive clears all +typemaps for a given type. For example:

+ + + +
+
%clear int; // Removes all types for int
%clear int *output, long *output;
+ + + +
+ + + +

Note: Since SWIG's default behavior is +defined by typemaps, clearing a fundamental type like int +will make that type unusable unless you also define a new set of +typemaps immediately after the clear operation.

+ + + +

30.7.5 +Placement of typemaps

+ + + +

Typemap declarations can be declared in the global scope, +within a C++ namespace, and within a C++ class. For example:

+ + + +
+
%typemap(in) int {
...
}

namespace std {
class string;
%typemap(in) string {
...
}
}

class Bar {
public:
typedef const int & const_reference;
%typemap(out) const_reference {
...
}
};
+ + + +
+ + + +

When a typemap appears inside a namespace or class, it stays +in effect until the end of the SWIG input (just like before). However, +the typemap takes the local scope into account. Therefore, this code

+ + + +
+
namespace std {
class string;
%typemap(in) string {
...
}
}
+ + + +
+ + + +

is really defining a typemap for the type std::string. +You could have code like this:

+ + + +
+
namespace std {
class string;
%typemap(in) string { /* std::string */
...
}
}

namespace Foo {
class string;
%typemap(in) string { /* Foo::string */
...
}
}
+ + + +
+ + + +

In this case, there are two completely distinct typemaps that +apply to two completely different types (std::string +and +Foo::string).

+ + + +

It should be noted that for scoping to work, SWIG has to know +that +string is a typename defined within a particular namespace. +In this example, this is done using the class declaration class +string +.

+ + + +

30.7.6 Ruby +typemaps

+ + + +

The following list details all of the typemap methods that can be used by the Ruby module:

-

%typemap(in)

+ +

30.7.6.1 + "in" typemap

-
Converts Ruby objects to input -function arguments
- -

%typemap(directorin)

- - -
Converts C++ objects in director -member functions to ruby objects.
- - -

%typemap(out)

- - -
Converts return value of a C function -to a Ruby object
- - -
- - -

%typemap(directorout)

- - -
Converts Ruby objects in director -member functions to C++ objects.
- - -

%typemap(varin)

- - -
Assigns a C global variable from a -Ruby object
- - -

%typemap(varout)

- - -
Returns a C global variable as a Ruby -object
- - -

%typemap(freearg)

- - -
Cleans up a function argument (if -necessary)
- - -

%typemap(argout)

- - -
Output argument processing
- - -

%typemap(directorargout)

- - -
Output argument processing in director -member functions.
- - -

%typemap(ret)

- - -
Cleanup of function return values
- - -

%typemap(memberin)

- - -
Setting of structure/class member data -
- - -

%typemap(globalin)

- - -
Setting of C global variables
- - -

%typemap(check)

- - -
Checks function input values.
- - -

%typemap(default)

- - -
Set a default value for an argument -(making it optional).
- - -

%typemap(arginit)

- - -
Initialize an argument to a value -before any conversions occur.
- - -

Examples of these typemaps appears in the section on typemap examples +

Converts Ruby objects to input +function arguments. For example:

-

30.7.3 Typemap + +
+
%typemap(in) int {
$1 = NUM2INT($input);
}
+ + + +
+ + + +

The following special variables are available:

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$input Input object +holding value to be converted.
$symname Name of +function/method being wrapped
$1...n Argument being +sent to the function
$1_name Name of the +argument (if provided)
$1_type The actual C +datatype matched by the typemap.
$1_ltype The assignable +version of the C datatype matched by the typemap.
+ + + +
+ + + +

This is probably the most commonly redefined typemap because +it can be used to implement customized conversions.

+ + + +

In addition, the "in" typemap allows the number of converted +arguments to be specified. For example:

+ + + +
+
// Ignored argument.
%typemap(in, numinputs=0) int *out (int temp) {
$1 = &temp;
}
+ + + +
+ + + +

At this time, only zero or one arguments may be converted.

+ + + +

30.7.6.2 +"typecheck" typemap

+ + + +

The "typecheck" typemap is used to support overloaded +functions and methods. It merely checks an argument to see whether or +not it matches a specific type. For example:

+ + + +
+
%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
$1 = FIXNUM_P($input) ? 1 : 0;
}
+ + + +
+ + + +

For typechecking, the $1 variable is always a simple integer +that is set to 1 or 0 depending on whether or not the input argument is +the correct type.

+ + + +

If you define new "in" typemaps and your +program uses overloaded methods, you should also define a collection of +"typecheck" typemaps. More details about this follow in a later section +on "Typemaps and Overloading."

+ + + +

30.7.6.3 + "out" typemap

+ + + +

Converts return value of a C function +to a Ruby object.

+ + + +

+ + + +%typemap(out) int {
+ + + +   $result = INT2NUM( $1 );
+ + + +}
+ + + +
+ + + +

The following special variables are available.

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$result Result object +returned to target language.
$symname Name of +function/method being wrapped
$1...n Argument being +wrapped
$1_name Name of the +argument (if provided)
$1_type The actual C +datatype matched by the typemap.
$1_ltype The assignable +version of the C datatype matched by the typemap.
+ + + +
+ + + +
+ + + +

30.7.6.4 +"arginit" typemap

+ + + +

The "arginit" typemap is used to set the initial value of a +function argument--before any conversion has occurred. This is not +normally necessary, but might be useful in highly specialized +applications. For example:

+ + + +
+
// Set argument to NULL before any conversion occurs
%typemap(arginit) int *data {
$1 = NULL;
}
+ + + +
+ + + +

30.7.6.5 +"default" typemap

+ + + +

The "default" typemap is used to turn an argument into a +default argument. For example:

+ + + +
+
%typemap(default) int flags {
$1 = DEFAULT_FLAGS;
}
...
int foo(int x, int y, int flags);
+ + + +
+ + + +

The primary use of this typemap is to either change the +wrapping of default arguments or specify a default argument in a +language where they aren't supported (like C). Target languages that do +not support optional arguments, such as Java and C#, effectively ignore +the value specified by this typemap as all arguments must be given.

+ + + +

Once a default typemap has been applied to an argument, all +arguments that follow must have default values. See the +Default/optional arguments section for further information on +default argument wrapping.

+ + + +

30.7.6.6 +"check" typemap

+ + + +

The "check" typemap is used to supply value checking code +during argument conversion. The typemap is applied after +arguments have been converted. For example:

+ + + +
+
%typemap(check) int positive {
if ($1 <= 0) {
SWIG_exception(SWIG_ValueError,"Expected positive value.");
}
}
+ + + +
+ + + +

30.7.6.7 +"argout" typemap

+ + + +

The "argout" typemap is used to return values from arguments. +This is most commonly used to write wrappers for C/C++ functions that +need to return multiple values. The "argout" typemap is almost always +combined with an "in" typemap---possibly to ignore the input value. For +example:

+ + + +
+
/* Set the input argument to point to a temporary variable */
%typemap(in, numinputs=0) int *out (int temp) {
$1 = &temp;
}

%typemap(argout, fragment="output_helper") int *out {
// Append output value $1 to $result (assuming a single integer in this case)
$result = output_helper( $result, INT2NUM(*$1) );
}
+ + + +
+ + + +

The following special variables are available.

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$result Result object +returned to target language.
$input The original +input object passed.
$symname Name of +function/method being wrapped.
+ + + +
+ + + +

The code supplied to the "argout" typemap is always placed +after the "out" typemap. If multiple return values are used, the extra +return values are often appended to return value of the function.

+ + + +

Output helper is a fragment that usually defines a macro to +some function like SWIG_Ruby_AppendOutput.

+ + + +

See the typemaps.i library for examples.

+ + + +

30.7.6.8 +"freearg" typemap

+ + + +

The "freearg" typemap is used to cleanup argument data. It is +only used when an argument might have allocated resources that need to +be cleaned up when the wrapper function exits. The "freearg" typemap +usually cleans up argument resources allocated by the "in" typemap. For +example:

+ + + +
+
// Get a list of integers
%typemap(in) int *items {
int nitems = Length($input);
$1 = (int *) malloc(sizeof(int)*nitems);
}
// Free the list
%typemap(freearg) int *items {
free($1);
}
+ + + +
+ + + +

The "freearg" typemap inserted at the end of the wrapper +function, just before control is returned back to the target language. +This code is also placed into a special variable $cleanup +that may be used in other typemaps whenever a wrapper function needs to +abort prematurely.

+ + + +

30.7.6.9 +"newfree" typemap

+ + + +

The "newfree" typemap is used in conjunction with the %newobject +directive and is used to deallocate memory used by the return result of +a function. For example:

+ + + +
+
%typemap(newfree) string * {
delete $1;
}
%typemap(out) string * {
$result = PyString_FromString($1->c_str());
}
...

%newobject foo;
...
string *foo();
+ + + +
+ + + +

See Object +ownership and %newobject for further details.

+ + + +

30.7.6.10 +"memberin" typemap

+ + + +

The "memberin" typemap is used to copy data from an +already converted input value into a structure member. It is +typically used to handle array members and other special cases. For +example:

+ + + +
+
%typemap(memberin) int [4] {
memmove($1, $input, 4*sizeof(int));
}
+ + + +
+ + + +

It is rarely necessary to write "memberin" typemaps---SWIG +already provides a default implementation for arrays, strings, and +other objects.

+ + + +

30.7.6.11 +"varin" typemap

+ + + +

The "varin" typemap is used to convert objects in the target +language to C for the purposes of assigning to a C/C++ global variable. +This is implementation specific.

+ + + +

30.7.6.12 +"varout" typemap

+ + + +

The "varout" typemap is used to convert a C/C++ object to an +object in the target language when reading a C/C++ global variable. +This is implementation specific.

+ + + +

30.7.6.13 +"throws" typemap

+ + + +

The "throws" typemap is only used when SWIG parses a C++ +method with an exception specification or has the %catches +feature attached to the method. It provides a default mechanism for +handling C++ methods that have declared the exceptions they will throw. +The purpose of this typemap is to convert a C++ exception into an error +or exception in the target language. It is slightly different to the +other typemaps as it is based around the exception type rather than the +type of a parameter or variable. For example:

+ + + +
+
%typemap(throws) const char * %{
rb_raise(rb_eRuntimeError, $1);
SWIG_fail;
%}
void bar() throw (const char *);
+ + + +
+ + + +

As can be seen from the generated code below, SWIG generates +an exception handler with the catch block comprising the "throws" +typemap content.

+ + + +
+
...
try {
bar();
}
catch(char const *_e) {
rb_raise(rb_eRuntimeError, _e);
SWIG_fail;
}
...
+ + + +
+ + + +

Note that if your methods do not have an exception +specification yet they do throw exceptions, SWIG cannot know how to +deal with them. For a neat way to handle these, see the Exception +handling with %exception section.

+ + + +

30.7.6.14 +"directorin" +typemap

+ + + +

Converts C++ objects in director +member functions to ruby objects. It is roughly the opposite +of the "in" typemap, making its typemap rule often similar to the "out" +typemap. +

+ + + +

+ + + +%typemap(directorin) int {
+ + + +     $result = INT2NUM($1);
+ + + +}
+ + + +
+ + + +

The following special variables are available.

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$result Result object +returned to target language.
$symname Name of +function/method being wrapped
$1...n Argument being +wrapped
$1_name Name of the +argument (if provided)
$1_type The actual C +datatype matched by the typemap.
$1_ltype The assignable +version of the C datatype matched by the typemap.
this C++ this, +referring to the class itself.
+ + + +
+ + + +

30.7.6.15 +"directorout" +typemap

+ + + +

Converts Ruby objects in director +member functions to C++ objects.  It is roughly the opposite +of the "out" typemap, making its rule often similar to the "in" +typemap. +

+ + + +

+ + + +%typemap(directorout) int {

+ + + +   $result = NUM2INT($1);

+ + + +}
+ + + +
+ + + +

The following special variables are available:

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$symname Name of +function/method being wrapped
$1...n Argument being +sent to the function
$1_name Name of the +argument (if provided)
$1_type The actual C +datatype matched by the typemap.
$1_ltype The assignable +version of the C datatype matched by the typemap.
this C++ this, +referring to the class itself.
+ + + +
+ + + +

Currently, the directorout nor the out typemap support the +option numoutputs, +but the Ruby module provides that functionality through a %feature +directive.  Thus, a function can be made to return "nothing" +if you do:

+ + + +
%feature("numoutputs","0") +MyClass::function;
+ + + +

This feature can be useful if a function returns a status +code, which you want to discard but still use the typemap to raise an +exception.
+ + + +

+ + + +

30.7.6.16 +"directorargout" +typemap

+ + + +

Output argument processing in director +member functions.

+ + + +
%typemap(directorargout, +fragment="output_helper") int {
+ + + +$result = output_helper( $result, NUM2INT($1) );

+ + + +}
+ + + +

The following special variables are available:

+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$resultResult that the +director function returns
$symnamename of the +function/method being wrapped
$1...nArgument being +sent to the function
$1_nameName of the +argument (if provided)
$1_typeThe actual C +datatype matched by the typemap
$1_ltypeThe assignable +version of the C datatype matched by the typemap
thisC++ this, +referring to the instance of the class itself
+ + + +
+ + + +

30.7.6.17 +"ret" +typemap

+ + + +

Cleanup of function return values +

+ + + +

30.7.6.18 +"globalin" +typemap

+ + + +

Setting of C global variables +

+ + + +

30.7.7 Typemap variables

+ +

Within a typemap, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables: +

+ + +

$1

+
A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that is @@ -2992,36 +5723,46 @@ supposed to hold an argument value. For output values, this is the raw result that is supposed to be returned to Ruby.
+

$input

+
A VALUE holding a raw Ruby object with an argument or variable value.
+

$result

+
A VALUE that holds the result to be returned to Ruby.
+

$1_name

+
The parameter name that was matched.
+

$1_type

+
The actual C datatype matched by the typemap.
+

$1_ltype

+
An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may @@ -3030,221 +5771,277 @@ and local variables in wrapper functions are declared using this type so that their values can be properly assigned.
+

$symname

+
The Ruby name of the wrapper function being created.
-

30.7.4 Useful + +

30.7.8 Useful Functions

+

When you write a typemap, you usually have to work directly with Ruby objects. The following functions may prove to be useful. (These functions plus many more can be found in Programming Ruby, by David Thomas and Andrew Hunt.)

+

 

-

30.7.4.1 C + +

30.7.8.1 C Datatypes to Ruby Objects

+
INT2NUM(long or int) - int to Fixnum or Bignum
INT2FIX(long or int) - int to Fixnum (faster than INT2NUM)
CHR2FIX(char) - char to Fixnum
rb_str_new2(char*) - char* to String
rb_float_new(double) - double to Float
+
-

30.7.4.2 Ruby + +

30.7.8.2 Ruby Objects to C Datatypes

+
 int NUM2INT(Numeric)
int FIX2INT(Numeric)
unsigned int NUM2UINT(Numeric)
unsigned int FIX2UINT(Numeric)
long NUM2LONG(Numeric)
long FIX2LONG(Numeric)
unsigned long FIX2ULONG(Numeric)
char NUM2CHR(Numeric or String)
char * STR2CSTR(String)
char * rb_str2cstr(String, int*length)
double NUM2DBL(Numeric)

+
-

30.7.4.3 Macros + +

30.7.8.3 Macros for VALUE

+

RSTRING_LEN(str)

+
length of the Ruby string
+

RSTRING_PTR(str)

+
pointer to string storage
+

RARRAY_LEN(arr)

+
length of the Ruby array
+

RARRAY(arr)->capa

+
capacity of the Ruby array
+

RARRAY_PTR(arr)

+
pointer to array storage
-

30.7.4.4 Exceptions

+ +

30.7.8.4 Exceptions

+

void rb_raise(VALUE exception, const char *fmt, ...)

+
Raises an exception. The given format string fmt and remaining arguments are interpreted as with printf().
+

void rb_fatal(const char *fmt, ...)

+
Raises a fatal exception, terminating the process. No rescue blocks are called, but ensure blocks will be called. The given format string fmt and remaining arguments are interpreted as with printf().
+

void rb_bug(const char *fmt, ...)

+
Terminates the process immediately -- no handlers of any sort will be called. The given format string fmt and remaining arguments are interpreted as with printf(). You should call this function only if a fatal bug has been exposed.
+

void rb_sys_fail(const char *msg)

+
Raises a platform-specific exception corresponding to the last known system error, with the given string msg.
+

VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, VALUE(*rescue)(VALUE, VALUE), VALUE rargs)

+
Executes body with the given args. If a StandardError exception is raised, then execute rescue with the given rargs.
+

VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, VALUE(*ensure)(VALUE), VALUE eargs)

+
Executes body with the given args. Whether or not an exception is raised, execute ensure with the given rargs after body has completed.
+

VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)

+
Executes body with the given args and returns nonzero in result if any exception was raised.
+

void rb_notimplement()

+
Raises a NotImpError exception to indicate that the enclosed function is not implemented yet, or not available on this platform.
+

void rb_exit(int status)

+
Exits Ruby with the given status. Raises a SystemExit exception and calls registered exit functions and finalizers.
+

void rb_warn(const char *fmt, ...)

+
Unconditionally issues a warning message to standard error. The given format string fmt and remaining arguments are interpreted as with printf().
+

void rb_warning(const char *fmt, ...)

+
Conditionally issues a warning message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf().
-

30.7.4.5 Iterators

+ +

30.7.8.5 Iterators

+

void rb_iter_break()

+
Breaks out of the enclosing iterator block.
+

VALUE rb_each(VALUE obj)

+
Invokes the each method of the given obj.
+

VALUE rb_yield(VALUE arg)

+
Transfers execution to the iterator block in the current context, passing arg as an argument. Multiple values may be passed in an array.
+

int rb_block_given_p()

+
Returns true if yield would execute a block in the current context; that is, if a code block was passed to the current method and is available to be called.
+

VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE (*block)(VALUE, VALUE), VALUE arg2)

+
Invokes method with argument args and block block. A yield from that method will invoke block @@ -3252,58 +6049,72 @@ with the argument given to yield, and a second argument arg2.
+

VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), VALUE value)

+
Equivalent to Ruby's catch.
+

void rb_throw(const char *tag, VALUE value)

+
Equivalent to Ruby's throw.
-

30.7.5 Typemap + +

30.7.9 Typemap Examples

+

This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.

-

30.7.6 Converting + +

30.7.10 Converting a Ruby array to a char **

+

A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Ruby Array instance to be used as a char ** object.

+
%module argv

// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
/* Get the length of the array */
int size = RARRAY($input)->len;
int i;
$1 = (char **) malloc((size+1)*sizeof(char *));
/* Get the first element in memory */
VALUE *ptr = RARRAY($input)->ptr;
for (i=0; i < size; i++, ptr++)
/* Convert Ruby Object String to char* */
$1[i]= STR2CSTR(*ptr);
$1[i]=NULL; /* End of list */
}

// This cleans up the char ** array created before
// the function call

%typemap(freearg) char ** {
free((char *) $1);
}

// Now a test function
%inline %{
int print_args(char **argv) {
int i = 0;
while (argv[i]) {
printf("argv[%d] = %s\n", i,argv[i]);
i++;
}
return i;
}
%}

+
+

When this module is compiled, the wrapped C function now operates as follows :

+
require 'Argv'
Argv.print_args(["Dave","Mike","Mary","Jane","John"])
argv[0] = Dave
argv[1] = Mike
argv[2] = Mary
argv[3] = Jane
argv[4] = John
+
+

In the example, two different typemaps are used. The "in" typemap is used to receive an input argument and convert it to a C array. Since dynamic memory allocation is used to allocate memory for @@ -3311,10 +6122,12 @@ the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

-

30.7.7 Collecting + +

30.7.11 Collecting arguments in a hash

+

Ruby's solution to the "keyword arguments" capability of some other languages is to allow the programmer to pass in one or more key-value pairs as arguments to a function. All of those key-value @@ -3325,24 +6138,30 @@ suppose you'd like to wrap this C function that collects information about people's vital statistics:

+
void setVitalStats(const char *person, int nattributes, const char **names, int *values);
+
+

and you'd like to be able to call it from Ruby by passing in an arbitrary number of key-value pairs as inputs, e.g.

+
setVitalStats("Fred",
'weight' => 270,
'age' => 42
)
+
+

To make this work, you need to write a typemap that expects a Ruby Hash as its input and somehow extracts the last three arguments (nattributes, names @@ -3350,13 +6169,16 @@ and values) needed by your C function. Let's start with the basics:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
}
+
+

This %typemap directive tells SWIG that we want to match any function declaration that has the specified types and names of arguments somewhere in the argument list. The fact that we @@ -3370,22 +6192,27 @@ and val) define local variables that our typemap will need.

+

Since we expect the input argument to be a Hash, let's next add a check for that:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
}
+
+

Check_Type() is just a macro (defined in the Ruby header files) that confirms that the input argument is of the correct type; if it isn't, an exception will be raised.

+

The next task is to determine how many key-value pairs are present in the hash; we'll assign this number to the first typemap argument ($1). This is a little tricky since the @@ -3395,75 +6222,93 @@ method directly and converting its result to a C int value:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
}
+
+

So now we know the number of attributes. Next we need to initialize the second and third typemap arguments (i.e. the two C arrays) to NULL and set the stage for extracting the keys and values from the hash:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
$2 = NULL;
$3 = NULL;
if ($1 > 0) {
$2 = (char **) malloc($1*sizeof(char *));
$3 = (int *) malloc($1*sizeof(int));
}

}
+
+

There are a number of ways we could extract the keys and values from the input hash, but the simplest approach is to first call the hash's keys method (which returns a Ruby array of the keys) and then start looping over the elements in that array:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
$2 = NULL;
$3 = NULL;
if ($1 > 0) {
$2 = (char **) malloc($1*sizeof(char *));
$3 = (int *) malloc($1*sizeof(int));
keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
for (i = 0; i < $1; i++) {
}

}
}
+
+

Recall that keys_arr and i are local variables for this typemap. For each element in the keys_arr array, we want to get the key itself, as well as the value corresponding to that key in the hash:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
$2 = NULL;
$3 = NULL;
if ($1 > 0) {
$2 = (char **) malloc($1*sizeof(char *));
$3 = (int *) malloc($1*sizeof(int));
keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
for (i = 0; i < $1; i++) {
key = rb_ary_entry(keys_arr, i);
val = rb_hash_aref($input, key);

}
}
}
+
+

To be safe, we should again use the Check_Type() macro to confirm that the key is a String and the value is a Fixnum:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
$2 = NULL;
$3 = NULL;
if ($1 > 0) {
$2 = (char **) malloc($1*sizeof(char *));
$3 = (int *) malloc($1*sizeof(int));
keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
for (i = 0; i < $1; i++) {
key = rb_ary_entry(keys_arr, i);
val = rb_hash_aref($input, key);
Check_Type(key, T_STRING);
Check_Type(val, T_FIXNUM);

}
}
}
+
+

Finally, we can convert these Ruby objects into their C equivalents and store them in our local C arrays:

+
%typemap(in) (int nattributes, const char **names, const int *values)
(VALUE keys_arr, int i, VALUE key, VALUE val) {
Check_Type($input, T_HASH);
$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
$2 = NULL;
$3 = NULL;
if ($1 > 0) {
$2 = (char **) malloc($1*sizeof(char *));
$3 = (int *) malloc($1*sizeof(int));
keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
for (i = 0; i < $1; i++) {
key = rb_ary_entry(keys_arr, i);
val = rb_hash_aref($input, key);
Check_Type(key, T_STRING);
Check_Type(val, T_FIXNUM);
$2[i] = STR2CSTR(key);
$3[i] = NUM2INT(val);

}
}
}
+
+

We're not done yet. Since we used malloc() to dynamically allocate the memory used for the names and values arguments, we need to provide a @@ -3471,32 +6316,39 @@ corresponding "freearg" typemap to free that memory so that there is no memory leak. Fortunately, this typemap is a lot easier to write:

+
%typemap(freearg) (int nattributes, const char **names, const int *values) {
free((void *) $2);
free((void *) $3);
}
+
+

All of the code for this example, as well as a sample Ruby program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

-

30.7.8 Pointer + +

30.7.12 Pointer handling

+

Occasionally, it might be necessary to convert pointer values that have been stored using the SWIG typed-pointer representation. Since there are several ways in which pointers can be represented, the following two functions are used to safely perform this conversion:

+

int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, int flags)

+
Converts a Ruby object obj to a C pointer whose address is ptr (i.e. ptr is a pointer to a pointer). The third argument, ty, @@ -3511,10 +6363,12 @@ but not raise an exception. If ty is NULL, no type-checking is performed.
+

VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)

+
Creates a new Ruby pointer object. Here, ptr is the pointer to convert, ty is the SWIG type descriptor structure that describes the type, and own @@ -3523,6 +6377,7 @@ the pointer (i.e. whether Ruby should free this data when the corresponding Ruby instance is garbage-collected).
+

Both of these functions require the use of a special SWIG type-descriptor structure. This structure contains information about the mangled name of the datatype, type-equivalence information, as well @@ -3531,63 +6386,77 @@ For a type of Foo *, the type descriptor structure is usually accessed as follows:

+
Foo *foo;
SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);

VALUE obj;
obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
+
+

In a typemap, the type descriptor should always be accessed using the special typemap variable $1_descriptor. For example:

+
%typemap(in) Foo * {
SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);
}
+
-

30.7.8.1 Ruby + +

30.7.12.1 Ruby Datatype Wrapping

+

VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void (*free)(void *), void *ptr)

+
Given a pointer ptr to some C data, and the two garbage collection routines for this data (mark and free), return a VALUE for the Ruby object.
+

VALUE Data_Make_Struct(VALUE class, c-type, void (*mark)(void *), void (*free)(void *), c-type *ptr)

+
Allocates a new instance of a C data type c-type, assigns it to the pointer ptr, then wraps that pointer with Data_Wrap_Struct() as above.
+

Data_Get_Struct(VALUE obj, c-type, c-type *ptr)

+
Retrieves the original C pointer of type c-type from the data object obj and assigns that pointer to ptr.
-

30.7.9 Example: + +

30.7.13 Example: STL Vector to Ruby Array

+

Another use for macros and type maps is to create a Ruby array from a STL vector of pointers. In essence, copy of all the pointers in the vector into a Ruby array. The use of the macro is to make the @@ -3597,62 +6466,78 @@ macro/typemap and should give insight into constructing similar typemaps for other STL structures:

+
%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
%typemap(out) vectorclassname &, const vectorclassname & {
VALUE arr = rb_ary_new2($1->size());
vectorclassname::iterator i = $1->begin(), iend = $1->end();
for ( ; i!=iend; i++ )
rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
$result = arr;
}
%typemap(out) vectorclassname, const vectorclassname {
VALUE arr = rb_ary_new2($1.size());
vectorclassname::iterator i = $1.begin(), iend = $1.end();
for ( ; i!=iend; i++ )
rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
$result = arr;
}
%enddef
+
+

Note, that the "c ## classname.klass" is used in the preprocessor step to determine the actual object from the class name.

+

To use the macro with a class Foo, the following is used:

+
PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
+
+

It is also possible to create a STL vector of Ruby objects:

+
%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
%typemap(in) vectorclassname &, const vectorclassname & {
Check_Type($input, T_ARRAY);
vectorclassname *vec = new vectorclassname;
int len = RARRAY($input)->len;
for (int i=0; i!=len; i++) {
VALUE inst = rb_ary_entry($input, i);
//The following _should_ work but doesn't on HPUX
// Check_Type(inst, T_DATA);
classname *element = NULL;
Data_Get_Struct(inst, classname, element);
vec->push_back(element);
}
$1 = vec;
}

%typemap(freearg) vectorclassname &, const vectorclassname & {
delete $1;
}
%enddef
+
+

It is also possible to create a Ruby array from a vector of static data types:

+
%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
%typemap(out) vectorclassname &, const vectorclassname & {
VALUE arr = rb_ary_new2($1->size());
vectorclassname::iterator i = $1->begin(), iend = $1->end();
for ( ; i!=iend; i++ )
rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
$result = arr;
}
%typemap(out) vectorclassname, const vectorclassname {
VALUE arr = rb_ary_new2($1.size());
vectorclassname::iterator i = $1.begin(), iend = $1.end();
for ( ; i!=iend; i++ )
rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
$result = arr;
}
%enddef
+
+
+ Note that this is mostly an example of typemaps. If you want to use the STL with ruby, you are advised to use the standard swig STL library, which does much more than this.  Refer to the section called the C++ Standard Template Library.
+

30.8 Docstring Features

+

Using ri and rdoc web pages in Ruby libraries is a common practice. Given the way that SWIG generates the extensions by default, your users @@ -3661,6 +6546,7 @@ any documentation for it, even if they run 'rdoc' on the resulting .c or .cxx file.

+

The features described in this section make it easy for you to add rdoc strings to your modules, functions and methods that can then be @@ -3668,23 +6554,28 @@ read by Ruby's rdoc tool to generate html web pages, ri documentation, Windows chm file and an .xml description.

+

rdoc can then be run from a console or shell window on a swig generated file. 

+

For example, to generate html web pages from a C++ file, you'd do: 

+
$ rdoc -E cxx=c -f html file_wrap.cxx
+

To generate ri documentation from a c wrap file, you could do:

+
$ rdoc -r file_wrap.c @@ -3696,6 +6587,7 @@ generate ri documentation from a c wrap file, you could do:
%module(docstring="This is the example module's docstring") example
+
+

When you have more than just a line or so then you can retain the easy readability of the %module directive by using a @@ -3719,17 +6614,21 @@ macro. For example:

+
%define DOCSTRING
"The `XmlResource` class allows program resources defining menus,
layout of controls on a panel, etc. to be loaded from an XML file."
%enddef

%module(docstring=DOCSTRING) xrc
+
+

30.8.2 %feature("autodoc")

+

Since SWIG does know everything about the function it wraps, it is possible to generate an rdoc containing the parameter types, names @@ -3738,6 +6637,7 @@ systems of any language, it makes sense to take advantage of it.

+

SWIG's Ruby module provides support for the "autodoc" feature, which when attached to a node in the parse tree will cause an rdoc @@ -3750,10 +6650,12 @@ feature, described below.

+

30.8.2.1 %feature("autodoc", "0")

+

When the "0" option is given then the types of the parameters will not be included in the autodoc string. For @@ -3762,29 +6664,36 @@ this function prototype:

+
%feature("autodoc", "0");
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
+
+

Then Ruby code like this will be generated:

+
function_name(x, y, foo=nil, bar=nil) -> bool
...
+
+

30.8.2.2 %feature("autodoc", "1")

+

When the "1" option is used then the parameter types will be used in the rdoc string. In addition, an attempt is made to @@ -3798,17 +6707,21 @@ this:

+
function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
...
+
+

30.8.2.3 %feature("autodoc", "2")

+

When the "2" option is used then the parameter types will not be @@ -3819,10 +6732,12 @@ this:

+

30.8.2.4 %feature("autodoc", "3")

+

When the "3" option is used then the function will be documented using a combination of "1" and "2" above.  Given the example above, @@ -3832,17 +6747,21 @@ this:

+
function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool

Parameters:
x - int
y - int
foo - Foo
bar - Bar
+
+

30.8.2.3 %feature("autodoc", "docstring")

+

Finally, there are times when the automatically generated autodoc string will make no sense for a Ruby programmer, particularly when a @@ -3852,17 +6771,21 @@ generated string. For example:

+
%feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
void GetPosition(int* OUTPUT, int* OUTPUT);
+
+

30.8.3 %feature("docstring")

+

In addition to the autodoc strings described above, you can also attach any arbitrary descriptive text to a node in the parse tree with @@ -3872,26 +6795,687 @@ If an item already has an autodoc string then it is combined with the docstring and they are output together.

+

30.9 Advanced Topics

+

30.9.1 Operator overloading

+

SWIG allows operator overloading with, by using the %extend or %rename commands in SWIG and the following operator names (derived from Python):

+
-
 General 
__repr__ - inspect
__str__ - to_s
__cmp__ - <=>
__hash__ - hash
__nonzero__ - nonzero?

Callable
__call__ - call

Collection
__len__ - length
__getitem__ - []
__setitem__ - []=

Numeric
__add__ - +
__sub__ - -
__mul__ - *
__div__ - /
__mod__ - %
__divmod__ - divmod
__pow__ - **
__lshift__ - <<
__rshift__ - >>
__and__ - &
__xor__ - ^
__or__ - |
__neg__ - -@
__pos__ - +@
__abs__ - abs
__invert__ - ~
__int__ - to_i
__float__ - to_f
__coerce__ - coerce

Additions in 1.3.13
__lt__ - <
__le__ - <=
__eq__ - ==
__gt__ - >
__ge__ - >=

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
General
__repr__ inspect
__str__ to_s
__cmp__ <=>
__hash__ hash
__nonzero__ nonzero?
Callable
__call__ call
Collection
__len__ length
__getitem__ []
__setitem__ []=
Numeric
__add__ +
__sub__ -
__mul__ *
__div__ /
__mod__ %
__divmod__ divmod
__pow__ **
__lshift__ <<
__rshift__ >>
__and__ &
__xor__ ^
__or__ |
__neg__ -@
__pos__ +@
__abs__ abs
__invert__ ~
__int__ to_i
__float__ to_f
__coerce__ coerce
Additions in 1.3.13
__lt__ <
__le__ <=
__eq__ ==
__gt__ >
__ge__ >=
+
+

Note that although SWIG supports the __eq__ magic method name for defining an equivalence operator, there is no separate method for handling inequality since Ruby @@ -3899,73 +7483,91 @@ parses the expression a != b as !(a == b).

+

30.9.2 Creating Multi-Module Packages

+

The chapter on Working with Modules discusses the basics of creating multi-module extensions with SWIG, and in particular the considerations for sharing runtime type information among the different modules.

+

As an example, consider one module's interface file (shape.i) that defines our base class:

+
%module shape

%{
#include "Shape.h"
%}

class Shape {
protected:
double xpos;
double ypos;
protected:
Shape(double x, double y);
public:
double getX() const;
double getY() const;
};
+
+

We also have a separate interface file (circle.i) that defines a derived class:

+
%module circle

%{
#include "Shape.h"
#include "Circle.h"
%}

// Import the base class definition from Shape module
%import shape.i

class Circle : public Shape {
protected:
double radius;
public:
Circle(double x, double y, double r);
double getRadius() const;
};
+
+

We'll start by building the Shape extension module:

+
$ swig -c++ -ruby shape.i
 
+
+

SWIG generates a wrapper file named shape_wrap.cxx. To compile this into a dynamically loadable extension for Ruby, prepare an extconf.rb script using this template:

+
require 'mkmf'

# Since the SWIG runtime support library for Ruby
# depends on the Ruby library, make sure it's in the list
# of libraries.
$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])

# Create the makefile
create_makefile('shape')
+
+

Run this script to create a Makefile and then type make to build the shared library:

+
$ ruby extconf.rb
creating Makefile
$ make
g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \
-I. -c shape_wrap.cxx
gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
-lruby -lruby -lc
+
+

Note that depending on your installation, the outputs may be slightly different; these outputs are those for a Linux-based development environment. The end result should be a shared library @@ -3974,91 +7576,113 @@ code. Now repeat this process in a separate directory for the Circle module:

+
    +
  1. Run SWIG to generate the wrapper code (circle_wrap.cxx);
  2. +
  3. Write an extconf.rb script that your end-users can use to create a platform-specific Makefile for the extension;
  4. +
  5. Build the shared library for this extension by typing make.
  6. +
+

Once you've built both of these extension modules, you can test them interactively in IRB to confirm that the Shape and Circle modules are properly loaded and initialized:

+
$ irb
irb(main):001:0> require 'shape'
true
irb(main):002:0> require 'circle'
true
irb(main):003:0> c = Circle::Circle.new(5, 5, 20)
#<Circle::Circle:0xa097208>
irb(main):004:0> c.kind_of? Shape::Shape
true
irb(main):005:0> c.getX()
5.0
+
+

30.9.3 Specifying Mixin Modules

+

The Ruby language doesn't support multiple inheritance, but it does allow you to mix one or more modules into a class using Ruby's include method. For example, if you have a Ruby class that defines an each instance method, e.g.

+
class Set
def initialize
@members = []
end

def each
@members.each { |m| yield m }
end
end
+
+

then you can mix-in Ruby's Enumerable module to easily add a lot of functionality to your class:

+
class Set
include Enumerable
def initialize
@members = []
end
def each
@members.each { |m| yield m }
end
end
+
+

To get the same benefit for your SWIG-wrapped classes, you can use the %mixin directive to specify the names of one or more modules that should be mixed-in to a class. For the above example, the SWIG interface specification might look like this:

+
%mixin Set "Enumerable";

class Set {
public:
// Constructor
Set();

// Iterates through set members
void each();
};
+
+

Multiple modules can be mixed into a class by providing a comma-separated list of module names to the %mixin directive, e.g.

+
%mixin Set "Fee,Fi,Fo,Fum";
+
+

Note that the %mixin directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter @@ -4066,40 +7690,49 @@ on "Customization Features") for more details).

+

30.10 Memory Management

+

One of the most common issues in generating SWIG bindings for Ruby is proper memory management. The key to proper memory management is clearly defining whether a wrapper Ruby object owns the underlying C struct or C++ class. There are two possibilities:

+ +

To complicate matters, object ownership may transfer from Ruby to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

+

30.10.1 Mark and Sweep Garbage Collector

+

Ruby uses a mark and sweep garbage collector. When the garbage collector runs, it finds all the "root" objects, including local variables, global variables, global constants, hardware registers and @@ -4115,11 +7748,13 @@ garbage collected. For more information about the Ruby garbage collector please refer to http://rubygarden.org/ruby/ruby?GCAndExtensions.

+

The Ruby C/API provides extension developers two hooks into the garbage collector - a "mark" function and a "sweep" function. By default these functions are set to NULL.

+

If a C struct or C++ class references any other Ruby objects, then it must provide a "mark" function. The "mark" function should identify any referenced Ruby objects by calling the rb_gc_mark function @@ -4127,16 +7762,19 @@ for each one. Unsurprisingly, this function will be called by the Ruby garbage during the "mark" phase.

+

During the sweep phase, Ruby destroys any unused objects. If any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

+

30.10.2 Object Ownership

+

As described above, memory management depends on clearly defining who is responsible for freeing the underlying C struct or C++ class. If the Ruby object is responsible for freeing the C++ object, @@ -4145,47 +7783,59 @@ object is not responsible for freeing the underlying memory, then a "free" function must not be registered for the object.

+

For the most part, SWIG takes care of memory management issues. The rules it uses are:

+ +

To make this clearer, let's look at an example. Assume we have a Foo and a Bar class.

+
/* File "RubyOwernshipExample.h" */

class Foo
{
public:
Foo() {}
~Foo() {}
};

class Bar
{
Foo *foo_;
public:
Bar(): foo_(new Foo) {}
~Bar() { delete foo_; }
Foo* get_foo() { return foo_; }
Foo* get_new_foo() { return new Foo; }
void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
};

+
+

First, consider this Ruby code:

+
foo = Foo.new
+
+

In this case, the Ruby code calls the underlying Foo C++ constructor, thus creating a new foo object. By default, SWIG will assign the new Ruby object a "free" function. @@ -4193,33 +7843,41 @@ When the Ruby object is garbage collected, the "free" function will be called. It in turn will call Foo's destructor.

+

Next, consider this code:

+
bar = Bar.new
foo = bar.get_foo()
+
+

In this case, the Ruby code calls a C++ member function, get_foo. By default, SWIG will not assign the Ruby object a "free" function. Thus, when the Ruby object is garbage collected the underlying C++ foo object is not affected.

+

Unfortunately, the real world is not as simple as the examples above. For example:

+
bar = Bar.new
foo = bar.get_new_foo()
+
+

In this case, the default SWIG behavior for calling member functions is incorrect. The Ruby object should assume ownership of the returned object. This can be done by using the %newobject directive. @@ -4227,16 +7885,20 @@ See

foo = Foo.new
bar = Bar.new
bar.set_foo(foo)
+ +

Without modification, this code will cause a segmentation fault. When the Ruby foo object goes out of scope, it will free the underlying C++ foo @@ -4248,70 +7910,89 @@ method is called. This can be done by using the special DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.

+

Thus, a correct SWIG interface file correct mapping for these classes is:

+
/* File RubyOwnershipExample.i */

%module RubyOwnershipExample

%{
#include "RubyOwnershipExample.h"
%}

class Foo
{
public:
Foo();
~Foo();
};

class Bar
{
Foo *foo_;
public:
Bar();
~Bar();
Foo* get_foo();

%newobject get_new_foo;
Foo* get_new_foo();

%apply SWIGTYPE *DISOWN {Foo *foo};
void set_foo(Foo *foo);
%clear Foo *foo;
};

+
+
+

This code can be seen in swig/examples/ruby/tracking.

+
+

30.10.3 Object Tracking

+

The remaining parts of this section will use the class library shown below to illustrate different memory management techniques. The class library models a zoo and the animals it contains.

+
%module zoo

%{
#include <string>
#include <vector>

#include "zoo.h"
%}

class Animal
{
private:
typedef std::vector<Animal*> AnimalsType;
typedef AnimalsType::iterator IterType;
protected:
AnimalsType animals;
protected:
std::string name_;
public:
// Construct an animal with this name
Animal(const char* name) : name_(name) {}

// Return the animal's name
const char* get_name() const { return name.c_str(); }
};

class Zoo
{
protected:
std::vector<animal *=""> animals;

public:
// Construct an empty zoo
Zoo() {}

/* Create a new animal. */
static Animal* Zoo::create_animal(const char* name)
{
return new Animal(name);
}

// Add a new animal to the zoo
void add_animal(Animal* animal) {
animals.push_back(animal);
}

Animal* remove_animal(size_t i) {
Animal* result = this->animals[i];
IterType iter = this->animals.begin();
std::advance(iter, i);
this->animals.erase(iter);

return result;
}

// Return the number of animals in the zoo
size_t get_num_animals() const {
return animals.size();
}

// Return a pointer to the ith animal
Animal* get_animal(size_t i) const {
return animals[i];
}
};

+
+

Let's say you SWIG this code and then run IRB:
+

+
$ irb
irb(main):001:0> require 'example'
=> true

irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
=> #<Example::Animal:0x2be3820>

irb(main):004:0> tiger1.get_name()
=> "tiger1"

irb(main):003:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2be0a60>

irb(main):006:0> zoo.add_animal(tiger)
=> nil

irb(main):007:0> zoo.get_num_animals()
=> 1

irb(main):007:0> tiger2 = zoo.remove_animal(0)
=> #<Example::Animal:0x2bd4a18>

irb(main):008:0> tiger2.get_name()
=> "tiger1"

irb(main):009:0> tiger1.equal?(tiger2)
=> false

+
+

Pay particular attention to the code tiger1.equal?(tiger2). Note that the two Ruby objects are not the same - but they reference the same underlying C++ object. This can cause problems. For example:
+

+
irb(main):010:0> tiger1 = nil
=> nil

irb(main):011:0> GC.start
=> nil

irb(main):012:0> tiger2.get_name()
(irb):12: [BUG] Segmentation fault

+
+

After the the garbage collector runs, as a result of our call to GC.start, callingtiger2.get_name() causes a segmentation fault. The problem is that when tiger1 @@ -4320,12 +8001,14 @@ calls the get_name() method it invokes it on a destroyed object.

+

This problem can be avoided if SWIG enforces a one-to-one mapping between Ruby objects and C++ classes. This can be done via the use of the %trackobjects functionality available in SWIG-1.3.26. and later.

+

When the %trackobjects is turned on, SWIG automatically keeps track of mappings between C++ objects and Ruby objects. Note that enabling object tracking causes a slight performance @@ -4333,6 +8016,7 @@ degradation. Test results show this degradation to be about 3% to 5% when creating and destroying 100,000 animals in a row.

+

Since %trackobjects is implemented as a %feature, it uses the same name matching rules as other kinds of features (see the chapter on @@ -4340,47 +8024,60 @@ the chapter on class-by-class basis if needed. To fix the example above:

+
+
%module example

%{
#include "example.h"
%}

/* Tell SWIG that create_animal creates a new object */
%newobject Zoo::create_animal;

/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
%trackobjects;

%include "example.h"
+
+

When this code runs we see:
+
+

+
$ irb
irb(main):001:0> require 'example'
=> true

irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
=> #<Example::Animal:0x2be37d8>

irb(main):003:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2be0a18>

irb(main):004:0> zoo.add_animal(tiger1)
=> nil

irb(main):006:0> tiger2 = zoo.remove_animal(0)
=> #<Example::Animal:0x2be37d8>

irb(main):007:0> tiger1.equal?(tiger2)
=> true

irb(main):008:0> tiger1 = nil
=> nil

irb(main):009:0> GC.start
=> nil

irb(main):010:0> tiger.get_name()
=> "tiger1"
irb(main):011:0>

+
+

For those who are interested, object tracking is implemented by storing Ruby objects in a hash table and keying them on C++ pointers. The underlying API is:
+

+
static void SWIG_RubyAddTracking(void* ptr, VALUE object);
static VALUE SWIG_RubyInstanceFor(void* ptr) ;
static void SWIG_RubyRemoveTracking(void* ptr);
static void SWIG_RubyUnlinkObjects(void* ptr);
+
+

When an object is created, SWIG will automatically call the SWIG_RubyAddTracking method. Similarly, when an object is deleted, SWIG will call the SWIG_RubyRemoveTracking. When an object is returned to Ruby from C++, SWIG will use the SWIG_RubyInstanceFor @@ -4389,6 +8086,7 @@ the RubyUnlinkObjects method unlinks a Ruby object from its underlying C++ object.

+

In general, you will only need to use the SWIG_RubyInstanceFor, which is required for implementing mark functions as shown below. However, if you implement your own free functions (see below) you may @@ -4396,30 +8094,37 @@ also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

+

30.10.4 Mark Functions

+

With a bit more testing, we see that our class library still has problems. For example:
+

+
$ irb
irb(main):001:0> require 'example'
=> true

irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
=> #<Example::Animal:0x2bea6a8>

irb(main):003:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2be7960>

irb(main):004:0> zoo.add_animal(tiger1)
=> nil

irb(main):007:0> tiger1 = nil
=> nil

irb(main):007:0> GC.start
=> nil

irb(main):005:0> tiger2 = zoo.get_animal(0)
(irb):12: [BUG] Segmentation fault
+
+

The problem is that Ruby does not know that the zoo object contains a reference to a Ruby object. Thus, when Ruby garbage collects tiger1 it frees the underlying C++ object.

+

This can be fixed by implementing a mark function as described above in the Mark and Sweep Garbage Collector section. You can specify a mark @@ -4430,6 +8135,7 @@ other kinds of features (see the chapter on for more details).

+

A mark function takes a single argument, which is a pointer to the C++ object being marked; it should, in turn, call rb_gc_mark() for any instances that are @@ -4440,13 +8146,16 @@ then call rb_gc_mark(). One possible implementation is:

+
%module example

%{
#include "example.h"
%}

/* Keep track of mappings between C/C++ structs/classes
and Ruby objects so we can implement a mark function. */
%trackobjects;

/* Specify the mark function */
%markfunc Zoo "mark_Zoo";

%include "example.h"

%header %{

static void mark_Zoo(void* ptr) {
Zoo* zoo = (Zoo*) ptr;

/* Loop over each object and tell the garbage collector
that we are holding a reference to them. */
int count = zoo->get_num_animals();

for(int i = 0; i < count; ++i) {
Animal* animal = zoo->get_animal(i);
VALUE object = SWIG_RubyInstanceFor(animal);

if (object != Qnil) {
rb_gc_mark(object);
}
}
}
%}

+
+

Note the mark function is dependent on the SWIG_RUBY_InstanceFor method, and thus requires that %trackobjects is enabled. For more @@ -4454,31 +8163,39 @@ information, please refer to the track_object.i test case in the SWIG test suite.

+

When this code is compiled we now see:

+
$ irb
irb(main):002:0> tiger1=Example::Animal.new("tiger1")
=> #<Example::Animal:0x2be3bf8>

irb(main):003:0> Example::Zoo.new()
=> #<Example::Zoo:0x2be1780>

irb(main):004:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2bde9c0>

irb(main):005:0> zoo.add_animal(tiger1)
=> nil

irb(main):009:0> tiger1 = nil
=> nil

irb(main):010:0> GC.start
=> nil
irb(main):014:0> tiger2 = zoo.get_animal(0)
=> #<Example::Animal:0x2be3bf8>

irb(main):015:0> tiger2.get_name()
=> "tiger1"
irb(main):016:0>

+
+
+

This code can be seen in swig/examples/ruby/mark_function.

+

30.10.5 Free Functions

+

By default, SWIG creates a "free" function that is called when a Ruby object is garbage collected. The free function simply calls the C++ object's destructor.

+

However, sometimes an appropriate destructor does not exist or special processing needs to be performed before the destructor is called. Therefore, SWIG allows you to manually specify a "free" @@ -4489,6 +8206,7 @@ for other kinds of features apply (see the chapter on ) for more details).

+

IMPORTANT ! - If you define your own free function, then you must ensure that you call the underlying C++ object's destructor. In addition, if object tracking is activated for the object's class, you @@ -4498,6 +8216,7 @@ that it is harmless to call this method if object tracking if off so it is advised to always call it.

+

Note there is a subtle interaction between object ownership and free functions. A custom defined free function will only be called if the Ruby object owns the underlying C++ object. This also to Ruby @@ -4506,6 +8225,7 @@ via the use of the disown typemap described above.

+

To show how to use the %freefunc directive, let's slightly change our example. Assume that the zoo object is responsible for freeing animal that it contains. This means @@ -4514,23 +8234,29 @@ function should be marked with a DISOWN +

Zoo::~Zoo() {
IterType iter = this->animals.begin();
IterType end = this->animals.end();

for(iter; iter != end; ++iter) {
Animal* animal = *iter;
delete animal;
}
}
+
+

When we use these objects in IRB we see:

+
$irb
irb(main):002:0> require 'example'
=> true

irb(main):003:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2be0fe8>

irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
=> #<Example::Animal:0x2bda760>

irb(main):006:0> zoo.add_animal(tiger1)
=> nil

irb(main):007:0> zoo = nil
=> nil

irb(main):008:0> GC.start
=> nil

irb(main):009:0> tiger1.get_name()
(irb):12: [BUG] Segmentation fault

+
+

The error happens because the C++ animal object is freed when the zoo object is freed. Although this error is unavoidable, we can at least prevent the @@ -4542,37 +8268,47 @@ longer valid. Once notified, SWIG will intercept any calls from the existing Ruby object to the destroyed C++ object and raise an exception.
+

+
%module example

%{
#include "example.h"
%}

/* Specify that ownership is transferred to the zoo
when calling add_animal */
%apply SWIGTYPE *DISOWN { Animal* animal };

/* Track objects */
%trackobjects;

/* Specify the mark function */
%freefunc Zoo "free_Zoo";

%include "example.h"

%header %{
static void free_Zoo(void* ptr) {
Zoo* zoo = (Zoo*) ptr;

/* Loop over each animal */
int count = zoo->get_num_animals();

for(int i = 0; i < count; ++i) {
/* Get an animal */
Animal* animal = zoo->get_animal(i);

/* Unlink the Ruby object from the C++ object */
SWIG_RubyUnlinkObjects(animal);

/* Now remove the tracking for this animal */
SWIG_RubyRemoveTracking(animal);
}

/* Now call SWIG_RemoveMapping for the zoo */
SWIG_RemoveMapping(ptr);

/* Now free the zoo which will free the animals it contains */
delete zoo;
}
%}
+
+

Now when we use these objects in IRB we see:

+
$irb
irb(main):002:0> require 'example'
=> true

irb(main):003:0> zoo = Example::Zoo.new()
=> #<Example::Zoo:0x2be0fe8>

irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
=> #<Example::Animal:0x2bda760>

irb(main):006:0> zoo.add_animal(tiger1)
=> nil

irb(main):007:0> zoo = nil
=> nil

irb(main):008:0> GC.start
=> nil

irb(main):009:0> tiger1.get_name()
RuntimeError: This Animal * already released
from (irb):10:in `get_name'
from (irb):10
irb(main):011:0>
+
+

Notice that SWIG can now detect the underlying C++ object has been freed, and thus raises a runtime exception.

+

This code can be seen in swig/examples/ruby/free_function.

+

30.10.6 Embedded Ruby and the C++ Stack

+

As has been said, the Ruby GC runs and marks objects before its sweep phase.  When the garbage collector is called, it will @@ -4581,13 +8317,16 @@ try to mark any Ruby objects (VALUE) it finds in the machine registers and in the C++ stack.

+

The stack is basically the history of the functions that have been called and also contains local variables, such as the ones you define -whenever you do:

+whenever you do inside a function:

-
VALUE obj;
+ +
VALUE obj;
+

For ruby to determine where its stack space begins, during @@ -4598,6 +8337,7 @@ where the stack points at at that point in time.

+

ruby_init() is presumed to always be called within the main() function of your program and whenever the GC is called, ruby will assume that the memory between the current location in memory and the @@ -4606,12 +8346,14 @@ contain local (and temporary) VALUE ruby objects.   Ruby will then be careful not to remove any of those objects in that location.

+

So far so good.  For a normal Ruby session, all the above is completely transparent and magic to the extensions developer.   

+

However, with an embedded Ruby, it may not always be possible to modify main() to make sure ruby_init() is called there.   As @@ -4626,42 +8368,52 @@ called.  The end result: random crashes and segmentation faults.

+

This problem will often be seen in director functions that are used for callbacks, for example.  

+

To solve the problem, SWIG can now generate code with director functions containing the optional macros SWIG_INIT_STACK and SWIG_RELEASE_STACK.   These macros will try to force Ruby to reinitiliaze the beginning of the stack the first time a director -function is called.  

+function is called.  This will lead Ruby to measure and not +collect any VALUE objects defined from that point on.  

+

To mark functions to either reset the ruby stack or not, you can use:

+
%initstack   Class::memberfunction;  // only re-init the stack in this director method
+ %ignorestack Class::memberfunction;  // do not re-init the stack in this director method
+ %initstack   Class;               // init the stack on all the methods of this class
+ %initstack;   // all director functions will re-init the stack
+

+ diff --git a/Lib/ruby/rubycontainer.swg b/Lib/ruby/rubycontainer.swg index d151adb84..331757698 100644 --- a/Lib/ruby/rubycontainer.swg +++ b/Lib/ruby/rubycontainer.swg @@ -159,7 +159,7 @@ namespace swig { %fragment("RubySequence_Cont","header", fragment="StdTraits", fragment="RubySequence_Base", - fragment="RubySwigIterator_T") + fragment="ConstIterator_T") { namespace swig { @@ -401,47 +401,85 @@ namespace swig */ %define %swig_sequence_iterator(Sequence...) #if defined(SWIG_EXPORT_ITERATOR_METHODS) - class iterator; - class reverse_iterator; - class const_iterator; - class const_reverse_iterator; %typemap(out,noblock=1,fragment="RubySequence_Cont") - iterator, reverse_iterator, const_iterator, const_reverse_iterator { + const_iterator, const_reverse_iterator { $result = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &)), - swig::RubySwigIterator::descriptor(),SWIG_POINTER_OWN); + swig::ConstIterator::descriptor(),SWIG_POINTER_OWN); } + %typemap(out,noblock=1,fragment="RubySequence_Cont") - std::pair, std::pair { + iterator, reverse_iterator { + $result = SWIG_NewPointerObj(swig::make_inout_iterator(%static_cast($1,const $type &)), + swig::Iterator::descriptor(),SWIG_POINTER_OWN); + } + + %typemap(out,noblock=1,fragment="RubySequence_Cont") + std::pair { $result = rb_ary_new2(2); RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first), - swig::RubySwigIterator::descriptor(),SWIG_POINTER_OWN); + swig::ConstIterator::descriptor(),SWIG_POINTER_OWN); RARRAY_PTR($result)[1] = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).second), - swig::RubySwigIterator::descriptor(),SWIG_POINTER_OWN); + swig::ConstIterator::descriptor(),SWIG_POINTER_OWN); RARRAY_LEN($result) = 2; } + %typemap(out,noblock=1,fragment="RubySequence_Cont") + std::pair { + $result = rb_ary_new2(2); + RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_inout_iterator(%static_cast($1,const $type &).first), + swig::Iterator::descriptor(),SWIG_POINTER_OWN); + RARRAY_PTR($result)[1] = SWIG_NewPointerObj(swig::make_inout_iterator(%static_cast($1,const $type &).second), + swig::Iterator::descriptor(),SWIG_POINTER_OWN); + RARRAY_LEN($result) = 2; + } + + %fragment("RubyPairBoolOutputIterator","header",fragment=SWIG_From_frag(bool),fragment="RubySequence_Cont") {} %typemap(out,noblock=1,fragment="RubyPairBoolOutputIterator") - std::pair, std::pair { + std::pair { $result = rb_ary_new2(2); RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_output_iterator(%static_cast($1,const $type &).first), - swig::RubySwigIterator::descriptor(),SWIG_POINTER_OWN); + swig::ConstIterator::descriptor(),SWIG_POINTER_OWN); + RARRAY_PTR($result)[1] = SWIG_From(bool)(%static_cast($1,const $type &).second); + RARRAY_LEN($result) = 2; + } + + %typemap(out,noblock=1,fragment="RubyPairBoolOutputIterator") + std::pair { + $result = rb_ary_new2(2); + RARRAY_PTR($result)[0] = SWIG_NewPointerObj(swig::make_inout_iterator(%static_cast($1,const $type &).first), + swig::Iterator::descriptor(),SWIG_POINTER_OWN); RARRAY_PTR($result)[1] = SWIG_From(bool)(%static_cast($1,const $type &).second); RARRAY_LEN($result) = 2; } %typemap(in,noblock=1,fragment="RubySequence_Cont") - iterator(swig::RubySwigIterator *iter = 0, int res), - reverse_iterator(swig::RubySwigIterator *iter = 0, int res), - const_iterator(swig::RubySwigIterator *iter = 0, int res), - const_reverse_iterator(swig::RubySwigIterator *iter = 0, int res) { - res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::RubySwigIterator::descriptor(), 0); + const_iterator(swig::ConstIterator *iter = 0, int res), + const_reverse_iterator(swig::ConstIterator *iter = 0, int res) { + res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), + swig::ConstIterator::descriptor(), 0); if (!SWIG_IsOK(res) || !iter) { %argument_fail(SWIG_TypeError, "$type", $symname, $argnum); } else { - swig::RubySwigIterator_T<$type > *iter_t = dynamic_cast *>(iter); + swig::ConstIterator_T<$type > *iter_t = dynamic_cast *>(iter); + if (iter_t) { + $1 = iter_t->get_current(); + } else { + %argument_fail(SWIG_TypeError, "$type", $symname, $argnum); + } + } + } + + %typemap(in,noblock=1,fragment="RubySequence_Cont") + iterator(swig::Iterator *iter = 0, int res), + reverse_iterator(swig::Iterator *iter = 0, int res) { + res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::Iterator::descriptor(), 0); + if (!SWIG_IsOK(res) || !iter) { + %argument_fail(SWIG_TypeError, "$type", $symname, $argnum); + } else { + swig::Iterator_T<$type > *iter_t = dynamic_cast *>(iter); if (iter_t) { $1 = iter_t->get_current(); } else { @@ -451,21 +489,35 @@ namespace swig } %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont") - iterator, reverse_iterator, const_iterator, const_reverse_iterator { - swig::RubySwigIterator *iter = 0; - int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::RubySwigIterator::descriptor(), 0); - $1 = (SWIG_IsOK(res) && iter && (dynamic_cast *>(iter) != 0)); + const_iterator, const_reverse_iterator { + swig::ConstIterator *iter = 0; + int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), swig::ConstIterator::descriptor(), 0); + $1 = (SWIG_IsOK(res) && iter && (dynamic_cast *>(iter) != 0)); + } + + %typecheck(%checkcode(ITERATOR),noblock=1,fragment="RubySequence_Cont") + iterator, reverse_iterator { + swig::ConstIterator *iter = 0; + int res = SWIG_ConvertPtr($input, %as_voidptrptr(&iter), + swig::Iterator::descriptor(), 0); + $1 = (SWIG_IsOK(res) && iter && (dynamic_cast *>(iter) != 0)); } %fragment("RubySequence_Cont"); - %newobject iterator; - %extend { - swig::RubySwigIterator* iterator(VALUE* RUBY_SELF) { - return swig::make_output_iterator($self->begin(), $self->begin(), - $self->end(), *RUBY_SELF); - } - } +// %newobject iterator; +// %newobject const_iterator; +// %extend { +// swig::Iterator* iterator(VALUE* RUBY_SELF) { +// return swig::make_inout_iterator($self->begin(), $self->begin(), +// $self->end(), *RUBY_SELF); +// } + +// swig::ConstIterator* const_iterator(VALUE* RUBY_SELF) { +// return swig::make_output_iterator($self->begin(), $self->begin(), +// $self->end(), *RUBY_SELF); +// } +// } #endif //SWIG_EXPORT_ITERATOR_METHODS %enddef diff --git a/Lib/ruby/rubyiterators.swg b/Lib/ruby/rubyiterators.swg index eafa265f4..1c3092419 100644 --- a/Lib/ruby/rubyiterators.swg +++ b/Lib/ruby/rubyiterators.swg @@ -6,9 +6,9 @@ * * Implement a C++ 'output' iterator for Ruby. * - * Users can derive form the RubySwigIterator to implemet their + * Users can derive form the Iterator to implemet their * own iterators. As an example (real one since we use it for STL/STD - * containers), the template RubySwigIterator_T does the + * containers), the template Iterator_T does the * implementation for generic C++ iterators. * ----------------------------------------------------------------------------- */ @@ -18,53 +18,48 @@ /** * Abstract base class used to represent all iterators of STL containers. */ -%fragment("RubySwigIterator","header") { +%fragment("ConstIterator","header") { namespace swig { struct stop_iteration { }; - struct RubySwigIterator { - private: + struct ConstIterator { + protected: VALUE _seq; protected: - RubySwigIterator(VALUE seq) : _seq(seq) + ConstIterator(VALUE seq) : _seq(seq) { } public: - virtual ~RubySwigIterator() {} + virtual ~ConstIterator() {} // Access iterator method, required by Ruby virtual VALUE value() const = 0; // Forward iterator method, required by Ruby - virtual RubySwigIterator *incr(size_t n = 1) = 0; + virtual ConstIterator *incr(size_t n = 1) = 0; // Backward iterator method, very common in C++, but not required in Ruby - virtual RubySwigIterator *decr(size_t n = 1) + virtual ConstIterator *decr(size_t n = 1) { throw stop_iteration(); } // Random access iterator methods, but not required in Ruby - virtual ptrdiff_t distance(const RubySwigIterator &x) const + virtual ptrdiff_t distance(const ConstIterator &x) const { throw std::invalid_argument("operation not supported"); } - virtual bool equal (const RubySwigIterator &x) const + virtual bool equal (const ConstIterator &x) const { throw std::invalid_argument("operation not supported"); } // C++ common/needed methods - virtual RubySwigIterator *copy() const = 0; - - virtual VALUE __deref__() - { - return Qnil; - } + virtual ConstIterator *dup() const = 0; VALUE next() { @@ -79,42 +74,42 @@ namespace swig { return value(); } - RubySwigIterator *advance(ptrdiff_t n) + ConstIterator *advance(ptrdiff_t n) { return (n > 0) ? incr(n) : decr(-n); } - bool operator == (const RubySwigIterator& x) const + bool operator == (const ConstIterator& x) const { return equal(x); } - bool operator != (const RubySwigIterator& x) const + bool operator != (const ConstIterator& x) const { return ! operator==(x); } - RubySwigIterator& operator += (ptrdiff_t n) + ConstIterator& operator += (ptrdiff_t n) { return *advance(n); } - RubySwigIterator& operator -= (ptrdiff_t n) + ConstIterator& operator -= (ptrdiff_t n) { return *advance(-n); } - RubySwigIterator* operator + (ptrdiff_t n) const + ConstIterator* operator + (ptrdiff_t n) const { - return copy()->advance(n); + return dup()->advance(n); } - RubySwigIterator* operator - (ptrdiff_t n) const + ConstIterator* operator - (ptrdiff_t n) const { - return copy()->advance(-n); + return dup()->advance(-n); } - ptrdiff_t operator - (const RubySwigIterator& x) const + ptrdiff_t operator - (const ConstIterator& x) const { return x.distance(*this); } @@ -123,33 +118,102 @@ namespace swig { static int init = 0; static swig_type_info* desc = 0; if (!init) { - desc = SWIG_TypeQuery("swig::RubySwigIterator *"); + desc = SWIG_TypeQuery("swig::ConstIterator *"); init = 1; } return desc; - } + } + + // Ruby common/needed printing methods + virtual VALUE inspect() const = 0; + virtual VALUE to_s() const = 0; }; + + struct Iterator : public ConstIterator { + protected: + Iterator(VALUE seq) : ConstIterator(seq) + { + } + + public: + // Iterator setter method, required by Ruby + virtual bool set( const VALUE& v ) = 0; + + static swig_type_info* descriptor() { + static int init = 0; + static swig_type_info* desc = 0; + if (!init) { + desc = SWIG_TypeQuery("swig::Iterator *"); + init = 1; + } + return desc; + } + + // C++ common/needed methods + virtual Iterator *dup() const = 0; + + Iterator *advance(ptrdiff_t n) + { + return (Iterator*) ( (n > 0) ? incr(n) : decr(-n) ); + } + + bool operator == (const ConstIterator& x) const + { + return equal(x); + } + + bool operator != (const Iterator& x) const + { + return ! operator==(x); + } + + Iterator& operator += (ptrdiff_t n) + { + return *advance(n); + } + + Iterator& operator -= (ptrdiff_t n) + { + return *advance(-n); + } + + Iterator* operator + (ptrdiff_t n) const + { + return dup()->advance(n); + } + + Iterator* operator - (ptrdiff_t n) const + { + return dup()->advance(-n); + } + + ptrdiff_t operator - (const Iterator& x) const + { + return x.distance(*this); + } + }; + } } -%fragment("RubySwigIterator_T","header",fragment="RubySwigIterator",fragment="StdTraits",fragment="StdIteratorTraits") { +%fragment("ConstIterator_T","header",fragment="ConstIterator",fragment="StdTraits",fragment="StdIteratorTraits") { namespace swig { /** - * Abstract base classes for all custom iterators. + * Abstract base classes for all custom const_iterators. * */ - template - class RubySwigIterator_T : public RubySwigIterator + template + class ConstIterator_T : public ConstIterator { public: - typedef OutIterator out_iterator; + typedef OutConstIterator out_iterator; typedef typename std::iterator_traits::value_type value_type; - typedef RubySwigIterator_T self_type; + typedef ConstIterator_T self_type; - RubySwigIterator_T(out_iterator curr, VALUE seq = Qnil) - : RubySwigIterator(seq), current(curr) + ConstIterator_T(out_iterator curr, VALUE seq = Qnil) + : ConstIterator(seq), current(curr) { } @@ -159,7 +223,7 @@ namespace swig { } - bool equal (const RubySwigIterator &iter) const + bool equal (const ConstIterator &iter) const { const self_type *iters = dynamic_cast(&iter); if (iters) { @@ -169,7 +233,7 @@ namespace swig { } } - ptrdiff_t distance(const RubySwigIterator &iter) const + virtual ptrdiff_t distance(const ConstIterator &iter) const { const self_type *iters = dynamic_cast(&iter); if (iters) { @@ -179,10 +243,110 @@ namespace swig { } } + virtual VALUE inspect() const + { + VALUE ret = rb_str_new2("#<"); + ret = rb_str_cat2( ret, rb_obj_classname(_seq) ); + ret = rb_str_cat2( ret, "::const_iterator " ); + VALUE cur = value(); + ret = rb_str_concat( ret, rb_inspect(cur) ); + ret = rb_str_cat2( ret, ">" ); + return ret; + } + + virtual VALUE to_s() const + { + VALUE ret = rb_str_new2( rb_obj_classname(_seq) ); + ret = rb_str_cat2( ret, "::const_iterator " ); + VALUE cur = value(); + ret = rb_str_concat( ret, rb_obj_as_string(cur) ); + return ret; + } + protected: out_iterator current; }; + + + /** + * Abstract base classes for all custom iterators. + * + */ + template + class Iterator_T : public Iterator + { + public: + typedef InOutIterator inout_iterator; + typedef typename std::iterator_traits::value_type value_type; + typedef Iterator_T self_type; + + Iterator_T(inout_iterator curr, VALUE seq = Qnil) + : Iterator(seq), current(curr) + { + } + + const inout_iterator& get_current() const + { + return current; + } + + bool equal (const ConstIterator &iter) const + { + const self_type *iters = dynamic_cast(&iter); + if (iters) { + return (current == iters->get_current()); + } else { + throw std::invalid_argument("bad iterator type"); + } + } + + virtual ptrdiff_t distance(const ConstIterator &iter) const + { + const self_type *iters = dynamic_cast(&iter); + if (iters) { + return std::distance(current, iters->get_current()); + } else { + throw std::invalid_argument("bad iterator type"); + } + } + + virtual VALUE inspect() const + { + VALUE ret = rb_str_new2("#<"); + ret = rb_str_cat2( ret, rb_obj_classname(_seq) ); + ret = rb_str_cat2( ret, "::iterator " ); + VALUE cur = value(); + ret = rb_str_concat( ret, rb_inspect(cur) ); + ret = rb_str_cat2( ret, ">" ); + return ret; + } + + virtual VALUE to_s() const + { + VALUE ret = rb_str_new2( rb_obj_classname(_seq) ); + ret = rb_str_cat2( ret, "::iterator " ); + VALUE cur = value(); + ret = rb_str_concat( ret, rb_obj_as_string(cur) ); + return ret; + } + + protected: + inout_iterator current; + }; + + + template + struct asval_oper + { + typedef ValueType value_type; + typedef bool result_type; + bool operator()(VALUE obj, value_type& v) const + { + return ( swig::asval< value_type >(obj, &v) == SWIG_OK ); + } + }; + template struct from_oper { @@ -196,23 +360,23 @@ namespace swig { /** - * Iterator class for a const_iterator with no end() boundaries. + * ConstIterator class for a const_iterator with no end() boundaries. * */ - template::value_type, + template::value_type, typename FromOper = from_oper > - class RubySwigIteratorOpen_T : public RubySwigIterator_T + class ConstIteratorOpen_T : public ConstIterator_T { public: FromOper from; - typedef OutIterator out_iterator; + typedef OutConstIterator out_iterator; typedef ValueType value_type; - typedef RubySwigIterator_T base; - typedef RubySwigIteratorOpen_T self_type; + typedef ConstIterator_T base; + typedef ConstIteratorOpen_T self_type; - RubySwigIteratorOpen_T(out_iterator curr, VALUE seq = Qnil) - : RubySwigIterator_T(curr, seq) + ConstIteratorOpen_T(out_iterator curr, VALUE seq = Qnil) + : ConstIterator_T(curr, seq) { } @@ -220,12 +384,12 @@ namespace swig { return from(static_cast(*(base::current))); } - RubySwigIterator *copy() const + ConstIterator *dup() const { return new self_type(*this); } - RubySwigIterator *incr(size_t n = 1) + ConstIterator *incr(size_t n = 1) { while (n--) { ++base::current; @@ -233,7 +397,7 @@ namespace swig { return this; } - RubySwigIterator *decr(size_t n = 1) + ConstIterator *decr(size_t n = 1) { while (n--) { --base::current; @@ -242,25 +406,80 @@ namespace swig { } }; - /** - * Iterator class for a const_iterator where begin() and end() boundaries are known. + * Iterator class for an iterator with no end() boundaries. * */ - template::value_type, + template::value_type, + typename FromOper = from_oper, + typename AsvalOper = asval_oper > + class IteratorOpen_T : public Iterator_T + { + public: + FromOper from; + AsvalOper asval; + typedef InOutIterator inout_iterator; + typedef ValueType value_type; + typedef Iterator_T base; + typedef IteratorOpen_T self_type; + + IteratorOpen_T(inout_iterator curr, VALUE seq = Qnil) + : Iterator_T(curr, seq) + { + } + + virtual VALUE value() const { + return from(static_cast(*(base::current))); + } + + virtual bool set( const VALUE& v ) + { + value_type& dst = *base::current; + return asval(v, dst); + } + + Iterator *dup() const + { + return new self_type(*this); + } + + Iterator *incr(size_t n = 1) + { + while (n--) { + ++base::current; + } + return this; + } + + Iterator *decr(size_t n = 1) + { + while (n--) { + --base::current; + } + return this; + } + }; + + /** + * ConstIterator class for a const_iterator where begin() and end() boundaries are known. + * + */ + template::value_type, typename FromOper = from_oper > - class RubySwigIteratorClosed_T : public RubySwigIterator_T + class ConstIteratorClosed_T : public ConstIterator_T { public: FromOper from; - typedef OutIterator out_iterator; + typedef OutConstIterator out_iterator; typedef ValueType value_type; - typedef RubySwigIterator_T base; - typedef RubySwigIteratorClosed_T self_type; + typedef ConstIterator_T base; + typedef ConstIteratorClosed_T self_type; - RubySwigIteratorClosed_T(out_iterator curr, out_iterator first, out_iterator last, VALUE seq = Qnil) - : RubySwigIterator_T(curr, seq), begin(first), end(last) + ConstIteratorClosed_T(out_iterator curr, out_iterator first, + out_iterator last, VALUE seq = Qnil) + : ConstIterator_T(curr, seq), begin(first), end(last) { } @@ -272,12 +491,13 @@ namespace swig { } } - RubySwigIterator *copy() const + + ConstIterator *dup() const { return new self_type(*this); } - RubySwigIterator *incr(size_t n = 1) + ConstIterator *incr(size_t n = 1) { while (n--) { if (base::current == end) { @@ -289,7 +509,7 @@ namespace swig { return this; } - RubySwigIterator *decr(size_t n = 1) + ConstIterator *decr(size_t n = 1) { while (n--) { if (base::current == begin) { @@ -306,6 +526,225 @@ namespace swig { out_iterator end; }; + /** + * Iterator class for a const_iterator where begin() and end() boundaries are known. + * + */ + template::value_type, + typename FromOper = from_oper, + typename AsvalOper = asval_oper > + class IteratorClosed_T : public Iterator_T + { + public: + FromOper from; + AsvalOper asval; + typedef InOutIterator inout_iterator; + typedef ValueType value_type; + typedef Iterator_T base; + typedef IteratorClosed_T self_type; + + IteratorClosed_T(inout_iterator curr, inout_iterator first, + inout_iterator last, VALUE seq = Qnil) + : Iterator_T(curr, seq), begin(first), end(last) + { + } + + virtual VALUE value() const { + if (base::current == end) { + throw stop_iteration(); + } else { + return from(static_cast(*(base::current))); + } + } + + // Iterator setter method, required by Ruby + virtual bool set( const VALUE& v ) + { + if (base::current == end) { + throw stop_iteration(); + } else { + value_type& dst = *base::current; + return asval( v, dst ); + } + } + + Iterator *dup() const + { + return new self_type(*this); + } + + Iterator *incr(size_t n = 1) + { + while (n--) { + if (base::current == end) { + throw stop_iteration(); + } else { + ++base::current; + } + } + return this; + } + + Iterator *decr(size_t n = 1) + { + while (n--) { + if (base::current == begin) { + throw stop_iteration(); + } else { + --base::current; + } + } + return this; + } + + private: + inout_iterator begin; + inout_iterator end; + }; + + /* Partial specialization for bools which don't allow de-referencing */ + template< typename InOutIterator, typename FromOper, typename AsvalOper > + class IteratorOpen_T< InOutIterator, bool, FromOper, AsvalOper > : + public Iterator_T + { + public: + FromOper from; + AsvalOper asval; + typedef InOutIterator inout_iterator; + typedef bool value_type; + typedef Iterator_T base; + typedef IteratorOpen_T self_type; + + IteratorOpen_T(inout_iterator curr, VALUE seq = Qnil) + : Iterator_T(curr, seq) + { + } + + virtual VALUE value() const { + return from(static_cast(*(base::current))); + } + + virtual bool set( const VALUE& v ) + { + return false; + } + + Iterator *dup() const + { + return new self_type(*this); + } + + Iterator *incr(size_t n = 1) + { + while (n--) { + ++base::current; + } + return this; + } + + Iterator *decr(size_t n = 1) + { + while (n--) { + --base::current; + } + return this; + } + + }; + + /* Partial specialization for bools which don't allow de-referencing */ + template< typename InOutIterator, typename FromOper, typename AsvalOper > + class IteratorClosed_T< InOutIterator, bool, FromOper, AsvalOper > : + public Iterator_T + { + public: + FromOper from; + AsvalOper asval; + typedef InOutIterator inout_iterator; + typedef bool value_type; + typedef Iterator_T base; + typedef IteratorClosed_T self_type; + + IteratorClosed_T(inout_iterator curr, inout_iterator first, + inout_iterator last, VALUE seq = Qnil) + : Iterator_T(curr, seq), begin(first), end(last) + { + } + + virtual VALUE value() const { + if (base::current == end) { + throw stop_iteration(); + } else { + return from(static_cast(*(base::current))); + } + } + + virtual bool set( const VALUE& v ) + { + return false; + } + + Iterator *dup() const + { + return new self_type(*this); + } + + Iterator *incr(size_t n = 1) + { + while (n--) { + if (base::current == end) { + throw stop_iteration(); + } else { + ++base::current; + } + } + return this; + } + + Iterator *decr(size_t n = 1) + { + while (n--) { + if (base::current == begin) { + throw stop_iteration(); + } else { + --base::current; + } + } + return this; + } + + private: + inout_iterator begin; + inout_iterator end; + + }; + + + /** + * Helper function used to wrap a bounded const_iterator. This is to be used in + * a %typemap(out), for example. + * + */ + template + inline Iterator* + make_inout_iterator(const InOutIter& current, const InOutIter& begin, + const InOutIter& end, VALUE seq = Qnil) + { + return new IteratorClosed_T(current, begin, end, seq); + } + + /** + * Helper function used to wrap an unbounded const_iterator. This is to be used in + * a %typemap(out), for example. + * + */ + template + inline Iterator* + make_inout_iterator(const InOutIter& current, VALUE seq = Qnil) + { + return new IteratorOpen_T(current, seq); + } /** * Helper function used to wrap a bounded const_iterator. This is to be used in @@ -313,10 +752,11 @@ namespace swig { * */ template - inline RubySwigIterator* - make_output_iterator(const OutIter& current, const OutIter& begin,const OutIter& end, VALUE seq = Qnil) + inline ConstIterator* + make_output_iterator(const OutIter& current, const OutIter& begin, + const OutIter& end, VALUE seq = Qnil) { - return new RubySwigIteratorClosed_T(current, begin, end, seq); + return new ConstIteratorClosed_T(current, begin, end, seq); } /** @@ -325,16 +765,16 @@ namespace swig { * */ template - inline RubySwigIterator* + inline ConstIterator* make_output_iterator(const OutIter& current, VALUE seq = Qnil) { - return new RubySwigIteratorOpen_T(current, seq); + return new ConstIteratorOpen_T(current, seq); } } } -%fragment("RubySwigIterator"); +%fragment("ConstIterator"); // @@ -357,59 +797,80 @@ namespace swig /* Mark methods that return new objects */ - %newobject RubySwigIterator::copy; - %newobject RubySwigIterator::operator + (ptrdiff_t n) const; - %newobject RubySwigIterator::operator - (ptrdiff_t n) const; + %newobject ConstIterator::dup; + %newobject ConstIterator::operator + (ptrdiff_t n) const; + %newobject ConstIterator::operator - (ptrdiff_t n) const; - %nodirector RubySwigIterator; + %nodirector ConstIterator; - %catches(swig::stop_iteration) RubySwigIterator::value() const; - %catches(swig::stop_iteration) RubySwigIterator::incr(size_t n = 1); - %catches(swig::stop_iteration) RubySwigIterator::decr(size_t n = 1); - %catches(std::invalid_argument) RubySwigIterator::distance(const RubySwigIterator &x) const; - %catches(std::invalid_argument) RubySwigIterator::equal (const RubySwigIterator &x) const; - %catches(swig::stop_iteration) RubySwigIterator::next(); - %catches(swig::stop_iteration) RubySwigIterator::previous(); - %catches(swig::stop_iteration) RubySwigIterator::advance(ptrdiff_t n); - %catches(swig::stop_iteration) RubySwigIterator::operator += (ptrdiff_t n); - %catches(swig::stop_iteration) RubySwigIterator::operator -= (ptrdiff_t n); - %catches(swig::stop_iteration) RubySwigIterator::operator + (ptrdiff_t n) const; - %catches(swig::stop_iteration) RubySwigIterator::operator - (ptrdiff_t n) const; + %catches(swig::stop_iteration) ConstIterator::value() const; + %catches(swig::stop_iteration) ConstIterator::incr(size_t n = 1); + %catches(swig::stop_iteration) ConstIterator::decr(size_t n = 1); + %catches(std::invalid_argument) ConstIterator::distance(const ConstIterator &x) const; + %catches(std::invalid_argument) ConstIterator::equal (const ConstIterator &x) const; + %catches(swig::stop_iteration) ConstIterator::next(); + %catches(swig::stop_iteration) ConstIterator::previous(); + %catches(swig::stop_iteration) ConstIterator::advance(ptrdiff_t n); + %catches(swig::stop_iteration) ConstIterator::operator += (ptrdiff_t n); + %catches(swig::stop_iteration) ConstIterator::operator -= (ptrdiff_t n); + %catches(swig::stop_iteration) ConstIterator::operator + (ptrdiff_t n) const; + %catches(swig::stop_iteration) ConstIterator::operator - (ptrdiff_t n) const; - struct RubySwigIterator + struct ConstIterator { protected: - RubySwigIterator(VALUE seq); + ConstIterator(VALUE seq); public: - virtual ~RubySwigIterator(); + virtual ~ConstIterator(); // Access iterator method, required by Ruby virtual VALUE value() const = 0; // Forward iterator method, required by Ruby - virtual RubySwigIterator *incr(size_t n = 1) = 0; + virtual ConstIterator *incr(size_t n = 1) = 0; // Backward iterator method, very common in C++, but not required in Ruby - virtual RubySwigIterator *decr(size_t n = 1); + virtual ConstIterator *decr(size_t n = 1); // Random access iterator methods, but not required in Ruby - virtual ptrdiff_t distance(const RubySwigIterator &x) const; + virtual ptrdiff_t distance(const ConstIterator &x) const; - virtual bool equal (const RubySwigIterator &x) const; + virtual bool equal (const ConstIterator &x) const; // C++ common/needed methods - virtual RubySwigIterator *copy() const = 0; + virtual ConstIterator *dup() const = 0; + + virtual VALUE inspect() const = 0; + virtual VALUE to_s() const = 0; VALUE next(); VALUE previous(); - RubySwigIterator *advance(ptrdiff_t n); + ConstIterator *advance(ptrdiff_t n); - bool operator == (const RubySwigIterator& x) const; - RubySwigIterator* operator + (ptrdiff_t n) const; - RubySwigIterator* operator - (ptrdiff_t n) const; - ptrdiff_t operator - (const RubySwigIterator& x) const; + bool operator == (const ConstIterator& x) const; + ConstIterator* operator + (ptrdiff_t n) const; + ConstIterator* operator - (ptrdiff_t n) const; + ptrdiff_t operator - (const ConstIterator& x) const; }; + + struct Iterator : public ConstIterator + { + virtual bool set( const VALUE& v ) = 0; + + // Random access iterator methods, but not required in Ruby + virtual ptrdiff_t distance(const Iterator &x) const; + virtual bool equal (const Iterator &x) const; + + virtual Iterator *dup() const = 0; + Iterator *advance(ptrdiff_t n); + + bool operator == (const Iterator& x) const; + Iterator* operator + (ptrdiff_t n) const; + Iterator* operator - (ptrdiff_t n) const; + ptrdiff_t operator - (const Iterator& x) const; + }; + } diff --git a/Lib/ruby/std_map.i b/Lib/ruby/std_map.i index cf06f0797..a102f4132 100644 --- a/Lib/ruby/std_map.i +++ b/Lib/ruby/std_map.i @@ -84,11 +84,12 @@ } }; - template - struct RubyMapIterator_T : RubySwigIteratorClosed_T + template + struct MapIterator_T : ConstIteratorClosed_T { - RubyMapIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) - : RubySwigIteratorClosed_T(curr, first, last, seq) + MapIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) + : ConstIteratorClosed_T(curr, first, last, seq) { } }; @@ -96,37 +97,39 @@ template > - struct RubyMapKeyIterator_T : RubyMapIterator_T + struct MapKeyIterator_T : MapIterator_T { - RubyMapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) - : RubyMapIterator_T(curr, first, last, seq) + MapKeyIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) + : MapIterator_T(curr, first, last, seq) { } }; template - inline RubySwigIterator* - make_output_key_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, VALUE seq = 0) + inline ConstIterator* + make_output_key_iterator(const OutIter& current, const OutIter& begin, + const OutIter& end, VALUE seq = 0) { - return new RubyMapKeyIterator_T(current, begin, end, seq); + return new MapKeyIterator_T(current, begin, end, seq); } template > - struct RubyMapValueIterator_T : RubyMapIterator_T + struct MapValueIterator_T : MapIterator_T { - RubyMapValueIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) - : RubyMapIterator_T(curr, first, last, seq) + MapValueIterator_T(OutIterator curr, OutIterator first, OutIterator last, VALUE seq) + : MapIterator_T(curr, first, last, seq) { } }; template - inline RubySwigIterator* - make_output_value_iterator(const OutIter& current, const OutIter& begin, const OutIter& end, VALUE seq = 0) + inline ConstIterator* + make_output_value_iterator(const OutIter& current, const OutIter& begin, + const OutIter& end, VALUE seq = 0) { - return new RubyMapValueIterator_T(current, begin, end, seq); + return new MapValueIterator_T(current, begin, end, seq); } } } @@ -309,13 +312,15 @@ } %newobject key_iterator(VALUE *RUBY_SELF); - swig::RubySwigIterator* key_iterator(VALUE *RUBY_SELF) { - return swig::make_output_key_iterator($self->begin(), $self->begin(), $self->end(), *RUBY_SELF); + swig::ConstIterator* key_iterator(VALUE *RUBY_SELF) { + return swig::make_output_key_iterator($self->begin(), $self->begin(), + $self->end(), *RUBY_SELF); } %newobject value_iterator(VALUE *RUBY_SELF); - swig::RubySwigIterator* value_iterator(VALUE *RUBY_SELF) { - return swig::make_output_value_iterator($self->begin(), $self->begin(), $self->end(), *RUBY_SELF); + swig::ConstIterator* value_iterator(VALUE *RUBY_SELF) { + return swig::make_output_value_iterator($self->begin(), $self->begin(), + $self->end(), *RUBY_SELF); } } diff --git a/Lib/ruby/std_set.i b/Lib/ruby/std_set.i index ab61a34e3..9f6967cf5 100644 --- a/Lib/ruby/std_set.i +++ b/Lib/ruby/std_set.i @@ -36,6 +36,7 @@ %} %define %swig_set_methods(set...) + %swig_sequence_iterator(set) %swig_sequence_methods_common(set); %extend { diff --git a/Lib/std/std_map.i b/Lib/std/std_map.i index 9851eb99d..05208418f 100644 --- a/Lib/std/std_map.i +++ b/Lib/std/std_map.i @@ -17,11 +17,8 @@ void erase(iterator first, iterator last); iterator find(const key_type& x); - const_iterator find(const key_type& x) const; iterator lower_bound(const key_type& x); - const_iterator lower_bound(const key_type& x) const; iterator upper_bound(const key_type& x); - const_iterator upper_bound(const key_type& x) const; #endif %enddef diff --git a/Lib/std/std_set.i b/Lib/std/std_set.i index 795144677..47d2af8aa 100644 --- a/Lib/std/std_set.i +++ b/Lib/std/std_set.i @@ -7,26 +7,35 @@ // Set %define %std_set_methods_common(set...) - %std_container_methods(set); + class const_iterator; + class const_reverse_iterator; + + set(); + set( const set& ); + const_iterator begin() const; + const_iterator end() const; + const_reverse_iterator rbegin(); + const_reverse_iterator rend(); + size_type erase(const key_type& x); size_type count(const key_type& x) const; #ifdef SWIG_EXPORT_ITERATOR_METHODS - void erase(iterator pos); - void erase(iterator first, iterator last); + void erase(const_iterator pos); + void erase(const_iterator first, const_iterator last); - iterator find(const key_type& x); - iterator lower_bound(const key_type& x); - iterator upper_bound(const key_type& x); - std::pair equal_range(const key_type& x); + const_iterator find(const key_type& x); + const_iterator lower_bound(const key_type& x); + const_iterator upper_bound(const key_type& x); + std::pair equal_range(const key_type& x); #endif %enddef %define %std_set_methods(set...) %std_set_methods_common(set); #ifdef SWIG_EXPORT_ITERATOR_METHODS - std::pair insert(const value_type& __x); + std::pair insert(const value_type& __x); #endif %enddef @@ -99,6 +108,5 @@ namespace std { #endif %std_set_methods(set); - }; } diff --git a/README b/README index 2241ef726..12ea20fff 100644 --- a/README +++ b/README @@ -27,11 +27,12 @@ Active Developers: Mikel Bancroft (mikel@franz.com) (Allegro CL) John Lenz (Guile, MzScheme updates, Chicken module, runtime system) Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) - Charlie Savage (cfis@interserv.com) (Ruby) Mark Gossage (mark@gossage.cjb.net) (Lua) Joseph Wang (joe@gnacademy.org) (R) + Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) Major contributors include: Lyle Johnson (lyle@users.sourceforge.net) (Ruby) + Charlie Savage (cfis@interserv.com) (Ruby) Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) Richard Palmer (richard@magicality.org) (PHP) Sam Liddicott - Anonova Ltd (saml@liddicott.com) (PHP)