1418
1449
<LI><A HREF="#Ruby_nn33">30.6 Exception handling</A>
1420
1451
<LI><A HREF="#Ruby_nn34">30.6.1 Using the %exception directive</A></LI>
1421
<LI><A HREF="#Ruby_nn35">30.6.2 Raising exceptions</A></LI>
1422
<LI><A HREF="#Ruby_nn36">30.6.3 Exception classes</A></LI>
1452
<LI><A HREF="#Ruby_nn34_2">30.6.2 Handling Ruby Blocks</A></LI>
1453
<LI><A HREF="#Ruby_nn35">30.6.3 Raising exceptions</A></LI>
1454
<LI><A HREF="#Ruby_nn36">30.6.4 Exception classes</A></LI>
1425
1457
<LI><A HREF="#Ruby_nn37">30.7 Typemaps</A>
1427
1459
<LI><A HREF="#Ruby_nn38">30.7.1 What is a typemap?</A></LI>
1428
<LI><A HREF="#Ruby_nn39">30.7.2 Ruby typemaps</A></LI>
1429
<LI><A HREF="#Ruby_nn40">30.7.3 Typemap variables</A></LI>
1430
<LI><A HREF="#Ruby_nn41">30.7.4 Useful Functions</A>
1432
<LI><A HREF="#Ruby_nn42">30.7.4.1 C Datatypes to Ruby Objects</A></LI>
1433
<LI><A HREF="#Ruby_nn43">30.7.4.2 Ruby Objects to C Datatypes</A></LI>
1434
<LI><A HREF="#Ruby_nn44">30.7.4.3 Macros for VALUE</A></LI>
1435
<LI><A HREF="#Ruby_nn45">30.7.4.4 Exceptions</A></LI>
1436
<LI><A HREF="#Ruby_nn46">30.7.4.5 Iterators</A></LI>
1439
<LI><A HREF="#Ruby_nn47">30.7.5 Typemap Examples</A></LI>
1440
<LI><A HREF="#Ruby_nn48">30.7.6 Converting a Ruby array to a char **</A></LI>
1441
<LI><A HREF="#Ruby_nn49">30.7.7 Collecting arguments in a hash</A></LI>
1442
<LI><A HREF="#Ruby_nn50">30.7.8 Pointer handling</A>
1444
<LI><A HREF="#Ruby_nn51">30.7.8.1 Ruby Datatype Wrapping</A></LI>
1447
<LI><A HREF="#Ruby_nn52">30.7.9 Example: STL Vector to Ruby Array</A></LI>
1450
<LI><A HREF="#Ruby_nn53">30.8 Advanced Topics</A>
1452
<LI><A HREF="#Ruby_nn54">30.8.1 Operator overloading</A></LI>
1453
<LI><A HREF="#Ruby_nn55">30.8.2 Creating Multi-Module Packages</A></LI>
1454
<LI><A HREF="#Ruby_nn56">30.8.3 Specifying Mixin Modules</A></LI>
1457
<LI><A HREF="#Ruby_nn57">30.9 Memory Management</A>
1459
<LI><A HREF="#Ruby_nn58">30.9.1 Mark and Sweep Garbage Collector</A></LI>
1460
<LI><A HREF="#Ruby_nn59">30.9.2 Object Ownership</A></LI>
1461
<LI><A HREF="#Ruby_nn60">30.9.3 Object Tracking</A></LI>
1462
<LI><A HREF="#Ruby_nn61">30.9.4 Mark Functions</A></LI>
1463
<LI><A HREF="#Ruby_nn62">30.9.5 Free Functions</A></LI>
1460
<LI><A HREF="#Ruby_Typemap_scope">30.7.2 Typemap scope</A></LI>
1461
<LI><A HREF="#Ruby_Copying_a_typemap">30.7.3 Copying a typemap</A></LI>
1462
<LI><A HREF="#Ruby_Deleting_a_typemap">30.7.4 Deleting a typemap</A></LI>
1463
<LI><A HREF="#Ruby_Placement_of_typemaps">30.7.5 Placement of typemaps</A>
1465
<LI><A HREF="#Ruby_nn39">30.7.6 Ruby typemaps</A>
1467
<LI><A HREF="#Ruby_in_typemap">30.7.6.1 "in" typemap</A></LI>
1468
<LI><A HREF="#Ruby_typecheck_typemap">30.7.6.2 "typecheck" typemap</A></LI>
1469
<LI><A HREF="#Ruby_out_typemap">30.7.6.3 "out" typemap</A></LI>
1470
<LI><A HREF="#Ruby_arginit_typemap">30.7.6.4 "arginit" typemap</A></LI>
1471
<LI><A HREF="#Ruby_default_typemap">30.7.6.5 "default" typemap</A></LI>
1472
<LI><A HREF="#Ruby_check_typemap">30.7.6.6 "check" typemap</A></LI>
1473
<LI><A HREF="#Ruby_argout_typemap_">30.7.6.7 "argout" typemap</A></LI>
1474
<LI><A HREF="#Ruby_freearg_typemap_">30.7.6.8 "freearg" typemap</A></LI>
1475
<LI><A HREF="#Ruby_newfree_typemap">30.7.6.9 "newfree" typemap</A></LI>
1476
<LI><A HREF="#Ruby_memberin_typemap">30.7.6.10 "memberin" typemap</A></LI>
1477
<LI><A HREF="#Ruby_varin_typemap">30.7.6.11 "varin" typemap</A></LI>
1478
<LI><A HREF="#Ruby_varout_typemap_">30.7.6.12 "varout" typemap</A></LI>
1479
<LI><A HREF="#Ruby_throws_typemap">30.7.6.13 "throws" typemap</A></LI>
1480
<LI><A HREF="#Ruby_directorin_typemap">30.7.6.14 directorin typemap</A></LI>
1481
<LI><A HREF="#Ruby_directorout_typemap">30.7.6.15 directorout typemap</A>
1483
<LI><A HREF="#Ruby_directorargout_typemap">30.7.6.16 directorargout
1485
<LI><A HREF="#Ruby_ret_typemap">30.7.6.17 ret typemap</A></LI>
1486
<LI><A HREF="#Ruby_globalin_typemap">30.7.6.18 globalin typemap</A></LI>
1489
<LI><A HREF="#Ruby_nn40">30.7.7 Typemap variables</A></LI>
1490
<LI><A HREF="#Ruby_nn41">30.7.8 Useful Functions</A>
1492
<LI><A HREF="#Ruby_nn42">30.7.8.1 C Datatypes to Ruby Objects</A></LI>
1493
<LI><A HREF="#Ruby_nn43">30.7.8.2 Ruby Objects to C Datatypes</A></LI>
1494
<LI><A HREF="#Ruby_nn44">30.7.8.3 Macros for VALUE</A></LI>
1495
<LI><A HREF="#Ruby_nn45">30.7.8.4 Exceptions</A></LI>
1496
<LI><A HREF="#Ruby_nn46">30.7.8.5 Iterators</A></LI>
1499
<LI><A HREF="#Ruby_nn47">30.7.9 Typemap Examples</A></LI>
1500
<LI><A HREF="#Ruby_nn48">30.7.10 Converting a Ruby array to a char **</A>
1502
<LI><A HREF="#Ruby_nn49">30.7.11 Collecting arguments in a hash</A></LI>
1503
<LI><A HREF="#Ruby_nn50">30.7.12 Pointer handling</A>
1505
<LI><A HREF="#Ruby_nn51">30.7.12.1 Ruby Datatype Wrapping</A></LI>
1508
<LI><A HREF="#Ruby_nn52">30.7.13 Example: STL Vector to Ruby Array</A></LI>
1511
<LI><A HREF="#Ruby_nn65">30.8 Docstring Features</A>
1513
<LI><A HREF="#Ruby_nn66">30.8.1 Module docstring</A></LI>
1514
<LI><A HREF="#Ruby_nn67">30.8.2 %feature("autodoc")</A>
1516
<LI><A HREF="#Ruby_nn68">30.8.2.1 %feature("autodoc", "0")</A></LI>
1517
<LI><A HREF="#Ruby_autodoc1">30.8.2.2 %feature("autodoc", "1")</A></LI>
1518
<LI><A HREF="#Ruby_autodoc2">30.8.2.3 %feature("autodoc", "2")</A></LI>
1519
<LI><A HREF="#Ruby_feature_autodoc3">30.8.2.4 %feature("autodoc", "3")</A>
1521
<LI><A HREF="#Ruby_nn70">30.8.2.5 %feature("autodoc", "docstring")</A></LI>
1524
<LI><A HREF="#Ruby_nn71">30.8.3 %feature("docstring")</A></LI>
1527
<LI><A HREF="#Ruby_nn53">30.9 Advanced Topics</A>
1529
<LI><A HREF="#Ruby_nn54">30.9.1 Operator overloading</A></LI>
1530
<LI><A HREF="#Ruby_nn55">30.9.2 Creating Multi-Module Packages</A></LI>
1531
<LI><A HREF="#Ruby_nn56">30.9.3 Specifying Mixin Modules</A></LI>
1534
<LI><A HREF="#Ruby_nn57">30.10 Memory Management</A>
1536
<LI><A HREF="#Ruby_nn58">30.10.1 Mark and Sweep Garbage Collector</A></LI>
1537
<LI><A HREF="#Ruby_nn59">30.10.2 Object Ownership</A></LI>
1538
<LI><A HREF="#Ruby_nn60">30.10.3 Object Tracking</A></LI>
1539
<LI><A HREF="#Ruby_nn61">30.10.4 Mark Functions</A></LI>
1540
<LI><A HREF="#Ruby_nn62">30.10.5 Free Functions</A></LI>
1541
<LI><A HREF="#Ruby_nn63">30.10.6 Embedded Ruby and the C++ Stack</A></LI>
19293
<H3><A name="csharp_date_marshalling"></A>17.5.3 Date marshalling using
19294
the csin typemap and associated attributes</H3>
19295
<P> The <A href="#nan_exception_typemap">NaN Exception example</A> is a
19296
simple example of the "javain" typemap and its 'pre' attribute. This
19297
example demonstrates how a C++ date class, say <TT>CDate</TT>, can be
19298
mapped onto the standard .NET date class, <TT>System.DateTime</TT> by
19299
using the 'pre', 'post' and 'pgcppname' attributes of the "csin"
19300
typemap (the C# equivalent to the "javain" typemap). The example is an
19301
equivalent to the <A href="#java_date_marshalling">Java Date
19302
marshalling example</A>. The idea is that the <TT>System.DateTime</TT>
19303
is used wherever the C++ API uses a <TT>CDate</TT>. Let's assume the
19304
code being wrapped is as follows:</P>
19309
CDate(int year, int month, int day);
19316
static int doSomething(const CDate &dateIn, CDate &dateOut);
19317
Action(const CDate &date, CDate &dateOut);
19321
<P> Note that <TT>dateIn</TT> is const and therefore read only and <TT>
19322
dateOut</TT> is a non-const output type.</P>
19323
<P> First let's look at the code that is generated by default, where the
19324
C# proxy class <TT>CDate</TT> is used in the proxy interface:</P>
19327
public class Action : IDisposable {
19329
public Action(CDate dateIn, CDate dateOut)
19330
: this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
19331
if (examplePINVOKE.SWIGPendingException.Pending)
19332
throw examplePINVOKE.SWIGPendingException.Retrieve();
19335
public int doSomething(CDate dateIn, CDate dateOut) {
19336
int ret = examplePINVOKE.Action_doSomething(swigCPtr,
19337
CDate.getCPtr(dateIn),
19338
CDate.getCPtr(dateOut));
19339
if (examplePINVOKE.SWIGPendingException.Pending)
19340
throw examplePINVOKE.SWIGPendingException.Retrieve();
19346
<P> The <TT>CDate &</TT> and <TT>const CDate &</TT> C# code is generated
19347
from the following two default typemaps:</P>
19350
%typemap(cstype) SWIGTYPE & "$csclassname"
19351
%typemap(csin) SWIGTYPE & "$csclassname.getCPtr($csinput)"
19354
<P> where '$csclassname' is translated into the proxy class name, <TT>
19355
CDate</TT> and '$csinput' is translated into the name of the parameter,
19356
eg <TT>dateIn</TT>. From C#, the intention is then to call into a
19357
modifed API with something like:</P>
19360
System.DateTime dateIn = new System.DateTime(2011, 4, 13);
19361
System.DateTime dateOut = new System.DateTime();
19363
// Note in calls below, dateIn remains unchanged and dateOut
19364
// is set to a new value by the C++ call
19365
Action action = new Action(dateIn, out dateOut);
19366
dateIn = new System.DateTime(2012, 7, 14);
19369
<P> To achieve this mapping, we need to alter the default code
19370
generation slightly so that at the C# layer, a <TT>System.DateTime</TT>
19371
is converted into a <TT>CDate</TT>. The intermediary layer will still
19372
take a pointer to the underlying <TT>CDate</TT> class. The typemaps to
19373
achieve this are shown below.</P>
19376
%typemap(cstype) const CDate& "System.DateTime"
19378
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);")
19380
"$csclassname.getCPtr(temp$csinput)"
19382
%typemap(cstype) CDate& "out System.DateTime"
19384
pre=" CDate temp$csinput = new CDate();",
19385
post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
19386
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
19387
cshin="out $csinput") CDate &
19388
"$csclassname.getCPtr(temp$csinput)"
19392
<P> The resulting generated proxy code in the <TT>Action</TT> class
19396
public class Action : IDisposable {
19398
public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
19399
CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
19400
CDate tempdateOut = new CDate();
19402
int ret = examplePINVOKE.Action_doSomething(swigCPtr,
19403
CDate.getCPtr(tempdateIn),
19404
CDate.getCPtr(tempdateOut));
19405
if (examplePINVOKE.SWIGPendingException.Pending)
19406
throw examplePINVOKE.SWIGPendingException.Retrieve();
19409
dateOut = new System.DateTime(tempdateOut.getYear(),
19410
tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
19414
static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
19415
CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
19416
CDate tempdateOut = new CDate();
19418
return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
19420
dateOut = new System.DateTime(tempdateOut.getYear(),
19421
tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
19425
public Action(System.DateTime dateIn, out System.DateTime dateOut)
19426
: this(Action.SwigConstructAction(dateIn, out dateOut), true) {
19427
if (examplePINVOKE.SWIGPendingException.Pending)
19428
throw examplePINVOKE.SWIGPendingException.Retrieve();
19433
<P> A few things to note:</P>
19435
<LI> The "cstype" typemap has changed the parameter type to <TT>
19436
System.DateTime</TT> instead of the default generated <TT>CDate</TT>
19438
<LI> The non-const <TT>CDate &</TT> type is marshalled as a reference
19439
parameter in C# as the date cannot be explicitly set once the object
19440
has been created, so a new object is created instead.</LI>
19441
<LI> The code in the 'pre' attribute appears before the intermediary
19442
call (<TT>examplePINVOKE.new_Action</TT> / <TT>
19443
examplePINVOKE.Action_doSomething</TT>).</LI>
19444
<LI> The code in the 'post' attribute appears after the intermediary
19446
<LI> A try .. finally block is generated with the intermediary call in
19447
the try block and 'post' code in the finally block. The alternative of
19448
just using a temporary variable for the return value from the
19449
intermediary call and the 'post' code being inserted before the return
19450
statement is not possible given that the intermediary call and method
19451
return comes from a single source (the "csout" typemap).</LI>
19452
<LI> The temporary variables in the "csin" typemaps are called <TT>
19453
temp$csin</TT>, where "$csin" is replaced with the parameter name.
19454
"$csin" is used to mangle the variable name so that more than one <TT>
19455
CDate &</TT> type can be used as a parameter in a method, otherwise two
19456
or more local variables with the same name would be generated.</LI>
19457
<LI> The use of the "csin" typemap causes a constructor helper function
19458
(<TT>SwigConstructAction</TT>) to be generated. This allows C# code to
19459
be called before the intermediary call made in the constructor
19460
initialization list.</LI>
19461
<LI> The 'cshin' attribute is required for the <TT>SwigConstructAction</TT>
19462
constructor helper function so that the 2nd parameter is declared as <TT>
19463
out dateOut</TT> instead of just <TT>dateOut</TT>.</LI>
19465
<P> So far we have considered the date as an input only and an output
19466
only type. Now let's consider <TT>CDate *</TT> used as an input/output
19467
type. Consider the following C++ function which modifies the date
19471
void addYears(CDate *pDate, int years) {
19472
*pDate = CDate(pDate->getYear() + years, pDate->getMonth(), pDate->getDay());
19476
<P> If usage of <TT>CDate *</TT> commonly follows this input/output
19477
pattern, usage from C# like the following</P>
19480
System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
19481
example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24
19484
<P> will be possible with the following <TT>CDate *</TT> typemaps</P>
19487
%typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
19490
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
19491
post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
19492
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
19493
cshin="ref $csinput") CDate *
19494
"$csclassname.getCPtr(temp$csinput)"
19497
<P> Globals are wrapped by the module class and for a module called
19498
example, the typemaps result in the following code:</P>
19501
public class example {
19502
public static void addYears(ref System.DateTime pDate, int years) {
19503
CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day);
19505
examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
19507
pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
19514
<H3><A name="csharp_date_properties"></A>17.5.4 A date example
19515
demonstrating marshalling of C# properties</H3>
19516
<P> The previous section looked at converting a C++ date class to <TT>
19517
System.DateTime</TT> for parameters. This section extends this idea so
19518
that the correct marshalling is obtained when wrapping C++ variables.
19519
Consider the same <TT>CDate</TT> class from the previous section and a
19520
global variable:</P>
19523
CDate ImportantDate = CDate(1999, 12, 31);
19526
<P> The aim is to use <TT>System.DateTime</TT> from C# when accessing
19527
this date as shown in the following usage where the module name is
19531
example.ImportantDate = new System.DateTime(2000, 11, 22);
19532
System.DateTime importantDate = example.ImportantDate;
19533
Console.WriteLine("Important date: " + importantDate);
19536
<P> When SWIG wraps a variable that is a class/struct/union, it is
19537
wrapped using a pointer to the type for the reasons given in <A href="#SWIG_structure_data_members">
19538
Stucture data members</A>. The typemap type required is thus <TT>CDate *</TT>
19539
. Given that the previous section already designed <TT>CDate *</TT>
19540
typemaps, we'll use those same typemaps plus the 'csvarin' and
19541
'csvarout' typemaps.<DIV class="code">
19543
%typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
19546
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
19547
post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
19548
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
19549
cshin="ref $csinput") CDate *
19550
"$csclassname.getCPtr(temp$csinput)"
19552
%typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
19553
/* csvarin typemap code */
19555
CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
19559
%typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
19560
/* csvarout typemap code */
19562
IntPtr cPtr = $imcall;
19563
CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
19564
return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
19569
<P> For a module called example, the typemaps result in the following
19573
public class example {
19574
public static System.DateTime ImportantDate {
19575
/* csvarin typemap code */
19577
CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
19578
examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
19580
/* csvarout typemap code */
19582
IntPtr cPtr = examplePINVOKE.ImportantDate_get();
19583
CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false);
19584
return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
19592
<P> Some points to note:</P>
19594
<LI>The property set comes from the 'csvarin' typemap and the property
19595
get comes from the 'csvarout' typemap.</LI>
19596
<LI>The type used for the property comes from the 'cstype' typemap. This
19597
particular example has the 'out' attribute set in the typemap and as it
19598
is specified, it is used in preference to the type in the typemap body.
19599
This is because the type in the 'out' attribute can never include
19600
modifiers such as 'ref', thereby avoiding code such as <TT>public
19601
static ref System.DateTime ImportantDate { ...</TT>, which would of
19602
course not compile.</LI>
19603
<LI>The <TT>$excode</TT> special variable expands to nothing as there
19604
are no exception handlers specified in any of the unmanaged code
19605
typemaps (in fact the marshalling was done using the default unmanaged
19606
code typemaps.)</LI>
19607
<LI>The <TT>$imcall</TT> typemap expands to the appropriate intermediary
19608
method call in the <TT>examplePINVOKE</TT> class.</LI>
19609
<LI>The <TT>$csinput</TT> special variable in the 'csin' typemap always
19610
expands to <TT>value</TT> for properties. In this case <TT>
19611
$csclassname.getCPtr(temp$csinput)</TT> expands to <TT>
19612
CDate.getCPtr(tempvalue)</TT>.</LI>
19613
<LI>The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and
19614
these are all ignored in the property set. The code in these attributes
19615
must instead be replicated within the 'csvarin' typemap. The line
19616
creating the <TT>temp$csinput</TT> variable is such an example; it is
19617
identical to what is in the 'pre' attribute.</LI>
19619
<H3><A name="csharp_partial_classes"></A>17.5.5 Turning wrapped classes
19620
into partial classes</H3>
19621
<P> C# supports the notion of partial classes whereby a class definition
19622
can be split into more than one file. It is possible to turn the
19623
wrapped C++ class into a partial C# class using the <TT>
19624
csclassmodifiers</TT> typemap. Consider a C++ class called <TT>ExtendMe</TT>
19630
int Part1() { return 1; }
19634
<P> The default C# proxy class generated is:</P>
19637
public class ExtendMe : IDisposable {
19639
public int Part1() {
19645
<P> The default csclassmodifiers typemap shipped with SWIG is</P>
19648
%typemap(csclassmodifiers) SWIGTYPE "public class"
19651
<P> Note that the type used is the special catch all type <TT>SWIGTYPE</TT>
19652
. If instead we use the following typemap to override this for just the <TT>
19653
ExtendMe</TT> class:</P>
19656
%typemap(csclassmodifiers) ExtendMe "public partial class"
19659
<P> The C# proxy class becomes a partial class:</P>
19662
public partial class ExtendMe : IDisposable {
19664
public int Part1() {
19670
<P> You can then of course declare another part of the partial class
19671
elsewhere, for example:</P>
19674
public partial class ExtendMe : IDisposable {
19675
public int Part2() {
19681
<P> and compile the following code:</P>
19684
ExtendMe em = new ExtendMe();
19685
Console.WriteLine("part1: {0}", em.Part1());
19686
Console.WriteLine("part2: {0}", em.Part2());
19689
<P> demonstrating that the class contains methods calling both unmanaged
19690
code - <TT>Part1()</TT> and managed code - <TT>Part2()</TT>. The
19691
following example is an alternative approach to adding managed code to
19692
the generated proxy class.</P>
19693
<H3><A name="csharp_extending_proxy_class"></A>17.5.6 Extending proxy
19694
classes with additional C# code</H3>
19695
<P> The previous example showed how to use partial classes to add
19696
functionality to a generated C# proxy class. It is also possible to
19697
extend a wrapped struct/class with C/C++ code by using the <A href="#SWIGPlus_class_extension">
19698
%extend directive</A>. A third approach is to add some C# methods into
19699
the generated proxy class with the <TT>cscode</TT> typemap. If we
19700
declare the following typemap before SWIG parses the <TT>ExtendMe</TT>
19701
class used in the previous example</P>
19704
%typemap(cscode) ExtendMe %{
19705
public int Part3() {
19712
<P> The generated C# proxy class will instead be:</P>
19715
public class ExtendMe : IDisposable {
19717
public int Part3() {
19720
public int Part1() {
18913
19725
</DIV><HR NOSHADE>
18915
19727
<!-- Hand-written HTML -->
26807
<H3><A name="java_date_marshalling"></A>20.9.13 Date marshalling using
26808
the javain typemap and associated attributes</H3>
26809
<P> The <A href="#nan_exception_typemap">NaN Exception example</A> is a
26810
simple example of the "javain" typemap and its 'pre' attribute. This
26811
example demonstrates how a C++ date class, say <TT>CDate</TT>, can be
26812
mapped onto the standard Java date class, <TT>
26813
java.util.GregorianCalendar</TT> by using the 'pre', 'post' and
26814
'pgcppname' attributes of the "javain" typemap. The idea is that the <TT>
26815
GregorianCalendar</TT> is used wherever the C++ API uses a <TT>CDate</TT>
26816
. Let's assume the code being wrapped is as follows:</P>
26821
CDate(int year, int month, int day);
26828
static int doSomething(const CDate &dateIn, CDate &dateOut);
26829
Action(const CDate &date, CDate &dateOut);
26833
<P> Note that <TT>dateIn</TT> is const and therefore read only and <TT>
26834
dateOut</TT> is a non-const output type.</P>
26835
<P> First let's look at the code that is generated by default, where the
26836
Java proxy class <TT>CDate</TT> is used in the proxy interface:</P>
26839
public class Action {
26841
public static int doSomething(CDate dateIn, CDate dateOut) {
26842
return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn,
26843
CDate.getCPtr(dateOut), dateOut);
26846
public Action(CDate date, CDate dateOut) {
26847
this(exampleJNI.new_Action(CDate.getCPtr(date), date,
26848
CDate.getCPtr(dateOut), dateOut), true);
26853
<P> The <TT>CDate &</TT> and <TT>const CDate &</TT> Java code is
26854
generated from the following two default typemaps:</P>
26857
%typemap(jstype) SWIGTYPE & "$javaclassname"
26858
%typemap(javain) SWIGTYPE & "$javaclassname.getCPtr($javainput)"
26861
<P> where '$javaclassname' is translated into the proxy class name, <TT>
26862
CDate</TT> and '$javainput' is translated into the name of the
26863
parameter, eg <TT>dateIn</TT>. From Java, the intention is then to call
26864
into a modifed API with something like:</P>
26867
java.util.GregorianCalendar calendarIn =
26868
new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
26869
java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();
26871
// Note in calls below, calendarIn remains unchanged and calendarOut
26872
// is set to a new value by the C++ call
26873
Action.doSomething(calendarIn, calendarOut);
26874
Action action = new Action(calendarIn, calendarOut);
26877
<P> To achieve this mapping, we need to alter the default code
26878
generation slightly so that at the Java layer, a <TT>GregorianCalendar</TT>
26879
is converted into a <TT>CDate</TT>. The JNI intermediary layer will
26880
still take a pointer to the underlying <TT>CDate</TT> class. The
26881
typemaps to achieve this are shown below.</P>
26884
%typemap(jstype) const CDate& "java.util.GregorianCalendar"
26886
pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
26887
"$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));",
26888
pgcppname="temp$javainput") const CDate &
26889
"$javaclassname.getCPtr(temp$javainput)"
26891
%typemap(jstype) CDate& "java.util.Calendar"
26893
pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
26894
"$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));",
26895
post=" $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), "
26896
"temp$javainput.getDay(), 0, 0, 0);",
26897
pgcppname="temp$javainput") CDate &
26898
"$javaclassname.getCPtr(temp$javainput)"
26901
<P> The resulting generated proxy code in the <TT>Action</TT> class
26905
public class Action {
26907
public static int doSomething(java.util.GregorianCalendar dateIn,
26908
java.util.Calendar dateOut) {
26909
CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR),
26910
dateIn.get(java.util.Calendar.MONTH),
26911
dateIn.get(java.util.Calendar.DATE));
26912
CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR),
26913
dateOut.get(java.util.Calendar.MONTH),
26914
dateOut.get(java.util.Calendar.DATE));
26916
return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn,
26917
CDate.getCPtr(tempdateOut), tempdateOut);
26919
dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
26923
static private long SwigConstructAction(java.util.GregorianCalendar date,
26924
java.util.Calendar dateOut) {
26925
CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR),
26926
date.get(java.util.Calendar.MONTH),
26927
date.get(java.util.Calendar.DATE));
26928
CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR),
26929
dateOut.get(java.util.Calendar.MONTH),
26930
dateOut.get(java.util.Calendar.DATE));
26932
return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate,
26933
CDate.getCPtr(tempdateOut), tempdateOut);
26935
dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
26939
public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
26940
this(Action.SwigConstructAction(date, dateOut), true);
26945
<P> A few things to note:</P>
26947
<LI> The "javatype" typemap has changed the parameter type to <TT>
26948
java.util.GregorianCalendar</TT> or <TT>java.util.Calendar</TT> instead
26949
of the default generated <TT>CDate</TT> proxy.</LI>
26950
<LI> The code in the 'pre' attribute appears before the JNI call (<TT>
26951
exampleJNI.new_Action</TT> / <TT>exampleJNI.Action_doSomething</TT>).</LI>
26952
<LI> The code in the 'post' attribute appears after the JNI call.</LI>
26953
<LI> A try .. finally block is generated with the JNI call in the try
26954
block and 'post' code in the finally block. The alternative of just
26955
using a temporary variable for the return value from the JNI call and
26956
the 'post' code being generated before the return statement is not
26957
possible given that the JNI call is in one line and comes from the
26958
"javaout" typemap.</LI>
26959
<LI> The temporary variables in the "javain" typemaps are called <TT>
26960
temp$javain</TT>, where "$javain" is replaced with the parameter name.
26961
"$javain" is used to mangle the variable name so that more than one <TT>
26962
CDate &</TT> type can be used as a parameter in a method, otherwise two
26963
or more local variables with the same name would be generated.</LI>
26964
<LI> The use of the "javain" typemap causes a constructor helper
26965
function (<TT>SwigConstructAction</TT>) to be generated. This allows
26966
Java code to be called before the JNI call and is required as the Java
26967
compiler won't compile code inserted before the 'this' call.</LI>
26968
<LI> The 'pgcppname' attribute is used to modify the object being passed
26969
as the <A href="#java_pgcpp">premature garbage collection prevention
26970
parameter</A> (the 2nd and 4th parameters in the JNI calls).</LI>
25742
26972
<H2><A name="java_directors_faq"></A>20.10 Living with Java Directors</H2>
25743
26973
<P> This section is intended to address frequently asked questions and
25744
26974
frequently encountered problems when using Java directors.</P>
31615
32913
<P> Swig can generate PHP extensions from C++ libraries as well when
31616
32914
given the <TT>-c++</TT> option. The support for C++ is discussed in
31617
32915
more detail in <A href="#Php_nn2_6">section 27.2.6</A>.</P>
31618
<P> To finish building the extension, you have two choices. The usual
31619
way is to build the extension as a separate dynamically loaded module.
31620
You can then specify that this be loaded automatically in <TT>php.ini</TT>
31621
or load it explicitly for any script which needs it. The alternative to
31622
creating a dynamically loaded module is to rebuild the entire php
31623
source tree and build the extension into the php executable/library so
31624
it will be available in every script. The first choice is the default,
31625
however it can be changed by passing the '-phpfull' command line switch
31626
to swig to select the second build method.</P>
32916
<P> The usual (and recommended) way is to build the extension as a
32917
separate dynamically loaded module. You can then specify that this be
32918
loaded automatically in <TT>php.ini</TT> or load it explicitly for any
32919
script which needs it.</P>
32920
<P> It is also possible to rebuild PHP from source so that your module
32921
is statically linked into the php executable/library. This is a lot
32922
more work, and also requires a full rebuild of PHP to update your
32923
module, and it doesn't play nicely with package system. We don't
32924
recommend this approach, but if you really want to do this, the <TT>
32925
-phpfull</TT> command line argument to swig may be of use - see below
31627
32927
<H3><A name="Php_nn1_1"></A>27.1.1 Building a loadable extension</H3>
31628
<P> There are two methods to build the extension as a dynamically loaded
31629
module: using standard compilation utilities (make, gcc), or using
31630
PHP's<EM> phpize</EM> utility.</P>
31631
<P> To build manually, use a compile string similar to this (different
32928
<P> To build your module as a dynamically loadable extension, use
32929
compilation commands like these (if you aren't using GCC, the commands
32930
will be different, and there may be so variation between platforms -
32931
these commands should at least work for Linux though):</P>
31633
32932
<DIV class="code">
31635
cc -I.. $(PHPINC) -fpic -c example_wrap.c
31636
cc -shared example_wrap.o -o example.so
32934
gcc `php-config --includes` -fpic -c example_wrap.c
32935
gcc -shared example_wrap.o -o example.so
31639
<P> The <TT>-make</TT> command line argument to swig will generate an
31640
additional file <TT>Makefile</TT> which can usually build the extension
31641
itself (on UNIX platforms).</P>
31642
<P> If you want to build your extension using the <TT>phpize</TT>
31643
utility, or if you want to build your module into PHP directly, you can
31644
specify the <TT>-phpfull</TT> command line argument to swig.</P>
31645
<P> The <TT>-phpfull</TT> will generate three additional files. The
31646
first extra file, <TT>config.m4</TT> contains the shell code needed to
31647
enable the extension as part of the PHP build process. The second extra
31648
file, <TT>Makefile.in</TT> contains the information needed to build the
31649
final Makefile after substitutions. The third and final extra file, <TT>
31650
CREDITS</TT> should contain the credits for the extension.</P>
32938
<P> There is a deprecated <TT>-make</TT> command line argument to swig
32939
which will generate an additional file <TT>makefile</TT> which can
32940
usually build the extension (at least on some UNIX platforms), but the
32941
Makefile generated isn't very flexible, and the commands required are
32942
trivial so it is simpler to just add them to your Makefile or other
32943
build system directly. We recommend that you don't use <TT>-make</TT>
32944
and it's likely to be removed at some point.</P>
32945
<H3><A name="Php_nn1_2"></A>27.1.2 Building extensions into PHP</H3>
32946
<P> Note that we don't recommend this approach - it's cleaner and
32947
simpler to use dynamically loadable modules, which are supported by all
32948
modern OSes. Support for this may be discontinued entirely in the
32950
<P> It is possible to rebuild PHP itself with your module statically
32951
linked in. To do this, you can use the <TT>-phpfull</TT> command line
32952
option to swig. Using this option will generate three additional files.
32953
The first extra file, <TT>config.m4</TT> contains the m4 and shell code
32954
needed to enable the extension as part of the PHP build process. The
32955
second extra file, <TT>Makefile.in</TT> contains the information needed
32956
to build the final Makefile after substitutions. The third and final
32957
extra file, <TT>CREDITS</TT> should contain the credits for the
31651
32959
<P> To build with phpize, after you have run swig you will need to run
31652
32960
the 'phpize' command (installed as part of php) in the same directory.
31653
32961
This re-creates the php build environment in that directory. It also
32672
34010
example</TT>, then a file <TT>example.py</TT> is created.</P>
32673
34011
<P> The following sections have further practical examples and details
32674
34012
on how you might go about compiling and using the generated files.</P>
32675
<DIV class="diagram">
32677
/usr/local/include/python2.0
32680
<P> The exact location may vary on your machine, but the above location
32681
is typical. If you are not entirely sure where Python is installed, you
32682
can run Python to find out. For example:</P>
32683
<DIV class="targetlang">
32686
Python 2.1.1 (#1, Jul 23 2001, 14:36:06)
32687
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
32688
Type "copyright", "credits" or "license" for more information.
32689
>>> import sys
32690
>>> print sys.prefix
32695
<H3><A name="Python_nn6"></A>29.2.2 Compiling a dynamic module</H3>
32696
<P> The preferred approach to building an extension module is to compile
32697
it into a shared object file or DLL. To do this, you need to compile
32698
your program using commands like this (shown for Linux):</P>
34013
<H3><A name="Python_nn6"></A>29.2.2 Using distutils</H3>
34014
<P> The preferred approach to building an extension module for python is
34015
to compile it with distutils, which comes with all recent versions of
34016
python (<A href="http://docs.python.org/dist/dist.html">Distutils Docs</A>
34018
<P> Distutils takes care of making sure that your extension is built
34019
with all the correct flags, headers, etc. for the version of Python it
34020
is run with. Distutils will compile your extension into a shared object
34021
file or DLL (<TT>.so</TT> on Linux, <TT>.pyd</TT> on Windows, etc). In
34022
addition, distutils can handle installing your package into
34023
site-packages, if that is desired. A configuration file (conventionally
34024
called: <TT>setup.py</TT>) describes the extension (and related python
34025
modules). The distutils will then generate all the right compiler
34026
directives to build it for you.</P>
34027
<P> Here is a sample <TT>setup.py</TT> file for the above example:</P>
34030
#!/usr/bin/env python
34033
setup.py file for SWIG example
34036
from distutils.core import setup, Extension
34039
example_module = Extension('_example',
34040
sources=['example_wrap.c', 'example.c'],
34043
setup (name = 'example',
34045
author = "SWIG Docs",
34046
description = """Simple swig example from docs""",
34047
ext_modules = [example_module],
34048
py_modules = ["example"],
34052
<P> In this example, the line: <TT>example_module = Extension(....)</TT>
34053
creates an Extension module object, defining the name as <TT>_example</TT>
34054
, and using the source code files: <TT>example_wrap.c</TT>, generated by
34055
swig, and <TT>example.c</TT>, your original c source. The swig (and
34056
other python extension modules) tradition is for the compiled extension
34057
to have the name of the python portion, prefixed by an underscore. If
34058
the name of your python module is "<TT>example.py</TT>", then the name
34059
of the corresponding object file will be"<TT>_example.so</TT>"</P>
34060
<P> The <TT>setup</TT> call then sets up distutils to build your
34061
package, defining some meta data, and passing in your extension module
34062
object. Once this is saved as <TT>setup.py</TT>, you can build your
34063
extension with these commands:</P>
34064
<DIV class="shell">
34066
$ swig -python example.i
34067
$ python setup.py build_ext --inplace
34070
<P> And a .so, or .pyd or... will be created for you. It will build a
34071
version that matches the python that you run the command with. Taking
34072
apart the command line:</P>
34074
<LI> <TT>python</TT> -- the version of python you want to build for</LI>
34075
<LI> <TT>setup.py</TT> -- the name of your setup script (it can be
34076
called anything, but setup.py is the tradition)</LI>
34077
<LI> <TT>build_ext</TT> -- telling distutils to build extensions</LI>
34078
<LI> <TT>--inplace</TT> -- this tells distutils to put the extension lib
34079
in the current dir. Other wise, it will put it inside a build
34080
hierarchy, and you'd have to move it to use it.</LI>
34082
<P> The distutils have many other features, consult the python distutils
34083
docs for details.</P>
34084
<P> This same approach works on all platforms if the appropriate
34085
compiler is installed. (it can even build extensions to the standard
34086
Windows Python using MingGW)</P>
34087
<H3><A name="Python_nn7"></A>29.2.3 Hand compiling a dynamic module</H3>
34088
<P> While the preferred approach to building an extension module is to
34089
use the distutils, some people like to integrate building extensions
34090
with a larger build system, and thus may wish to compile their modules
34091
without the distutils. To do this, you need to compile your program
34092
using commands like this (shown for Linux):</P>
32699
34093
<DIV class="shell">
32701
34095
$ swig -python example.i
37081
38546
<BR>float sum(const std::vector<float>& values);
37084
<P> Obviously, there is a lot more to template wrapping than shown in
38549
<P>Ruby's STL wrappings provide additional methods to make them behave
38550
more similarly to Ruby's native classes.</P>
38551
<P>Thus, you can do, for example:</P>
38552
<DIV class="targetlang">
38553
<PRE>v = IntVector.new
38554
<!--span class="targetlang"-->
38556
<!--span class="targetlang"-->
38559
<BR>v.each { |x| puts x }
38561
<!--span style="font-weight: bold;"-->
38563
<BR style="font-weight: bold;">
38564
<!--span style="font-weight: bold;"-->
38566
<BR style="font-weight: bold;">
38567
<!--span style="font-weight: bold;"-->
38569
<BR>v.delete_if { |x| x == 3 }
38571
<!--span style="font-weight: bold;"-->
38574
<P>The SWIG Ruby module provides also the ability for all the STL
38575
containers to carry around Ruby native objects (Fixnum, Classes, etc)
38576
making them act almost like Ruby's own Array, Hash, etc. To do that,
38577
you need to define a container that contains a swig::GC_VALUE, like:</P>
38578
<DIV class="code" style="font-family: monospace;">%module nativevector
38581
<BR> std::vector< swig::GC_VALUE > NativeVector;
38584
<BR> %template(NativeVector) std::vector< swig::GC_VALUE >;
38587
<P>This vector can then contain any Ruby object, making them almost
38588
identical to Ruby's own Array class.</P>
38589
<DIV class="targetlang">
38590
<!--span style="font-family: monospace;"-->
38591
require 'nativevector'
38592
<BR style="font-family: monospace;">
38593
<!--span style="font-family: monospace;"-->
38594
include NativeVector
38595
<BR style="font-family: monospace;">
38596
<BR style="font-family: monospace;">
38597
<!--span style="font-family: monospace;"-->
38598
v = NativeVector.new
38599
<BR style="font-family: monospace;">
38600
<!--span style="font-family: monospace;"-->
38602
<BR style="font-family: monospace;">
38603
<!--span style="font-family: monospace;"-->
38605
<BR style="font-family: monospace;">
38606
<!--span style="font-family: monospace;"-->
38608
<BR style="font-family: monospace;">
38609
<BR style="font-family: monospace;">
38610
<!--span style="font-family: monospace;"-->
38612
<BR style="font-family: monospace;">
38613
<BR style="font-family: monospace;">
38614
<!--span style="font-family: monospace;"-->
38616
<BR style="font-family: monospace;">
38617
<BR style="font-family: monospace;">
38618
<!--span style="font-family: monospace;"-->
38620
<BR style="font-family: monospace;">
38621
<!--span style="font-weight: bold; font-family: monospace;"-->
38622
=> [1, [1,2], 'hello', #<A:0x245325>]</DIV>
38624
<P>Obviously, there is a lot more to template wrapping than shown in
37085
38625
these examples. More details can be found in the <A href="#SWIGPlus">
37086
38626
SWIG and C++</A> chapter.</P>
37087
<H3><A name="Ruby_nn24"></A>30.3.13 C++ Smart Pointers</H3>
38627
<H3><A name="C_STL_Functors"></A>30.3.14 C++ STL Functors</H3>
38628
<P>Some containers in the STL allow you to modify their default behavior
38629
by using so called functors or function objects. Functors are often
38630
just a very simple struct with
38631
<!--span style="font-family: monospace;"-->
38632
operator() redefined or an actual C/C++ function. This allows you, for
38633
example, to always keep the sort order of a STL container to your
38635
<P>The Ruby STL mappings allows you to modify those containers that
38636
support functors using Ruby procs or methods, instead. Currently, this
38638
<!--span style="font-family: monospace;"-->
38640
<!--span style="font-family: monospace;"-->
38642
<!--span style="font-family: monospace;"-->
38644
<!--span style="font-family: monospace;"-->
38646
<P>The functors in swig are called
38647
<!--span style="font-family: monospace;"-->
38648
swig::UnaryFunction and
38649
<!--span style="font-family: monospace;"-->
38650
swig::BinaryFunction.
38651
<BR> For C++ predicates (ie. functors that must return bool as a result)
38652
<!--span style="font-family: monospace;"-->
38653
swig::UnaryPredicate and
38654
<!--span style="font-family: monospace;"-->
38655
swig::BinaryPredicate are provided.</P>
38656
<P>As an example, if given this swig file:</P>
38657
<DIV class="code" style="font-family: monospace;">%module intset;
38659
<BR> %include std_set.i
38661
<BR> %typemap(IntSet) std::set< int, swig::BinaryPredicate >;</DIV>
38662
<P>You can then use the set from Ruby with or without a proc object as a
38664
<DIV class="targetlang" style="font-family: monospace;">require 'intset'
38665
<BR> include Intset
38667
<BR> # Default sorting behavior defined in C++
38668
<BR> a = IntSet.new
38674
<!--span style="font-weight: bold;"-->
38675
=> [1,2,3]
38677
<BR> # Custom sorting behavior defined by a Ruby proc<DIV>
38678
<!--span class="targetlang"-->
38679
b = IntSet.new( proc { |a,b| a > b } )
38680
<BR> b << 1
38681
<BR> b << 2
38682
<BR> b << 3
38684
<BR style="font-weight: bold;">
38685
<!--span style="font-weight: bold;"-->
38686
=> [3,2,1]</DIV></DIV>
38687
<H3><A name="Ruby_C_Iterators"></A>30.3.15 C++ STL Iterators</H3>
38688
<P>The STL is well known for the use of iterators. There are a number
38689
of iterators possible with different properties, but in general there
38690
are two main categories: const iterators and non-const iterators. The
38691
const iterators can access and not modify the values they point at,
38692
while the non-const iterators can both read and modify the values.</P>
38693
<P>The Ruby STL wrappings support both type of iterators by using a
38694
proxy class in-between. This proxy class is
38695
<!--span style="font-family: monospace;"-->
38696
swig::Iterator or swig::ConstIterator. Derived from them are template
38697
classes that need to be initialized with the actual iterator for the
38698
container you are wrapping and often times with the beginning and
38699
ending points of the iteration range. </P>
38700
<P>The SWIG STL library already provides typemaps to all the standard
38701
containers to do this wrapping automatically for you, but if you have
38702
your own STL-like iterator, you will need to write your own typemap for
38703
them. For out typemaps, the special functions
38704
<!--span style="font-family: monospace;"-->
38705
make_const_iterator and
38706
<!--span style="font-family: monospace;"-->
38707
make_nonconst_iterator are provided.</P>
38708
<P>These can be used either like:</P>
38709
<DIV class="code" style="font-family: monospace;">make_const_iterator(
38710
iterator, rubyclass );
38711
<BR> make_const_iterator( iterator, iterator_begin, iterator_end,
38713
<P>The iterators support a
38714
<!--span style="font-family: monospace;"-->
38716
<!--span style="font-family: monospace;"-->
38717
previous() member function to just change the iterator without
38718
returning anything.
38719
<!--span style="font-family: monospace;"-->
38720
previous() should obviously only be used for bidirectional iterators.
38721
You can also advance the iterator multiple steps by using standard
38722
math operations like
38723
<!--span style="font-family: monospace;"-->
38725
<P>The value the iterator points at can be accessed with
38726
<!--span style="font-family: monospace;"-->
38727
value() -- this is equivalent to dereferencing it with
38728
<!--span style="font-family: monospace;"-->
38729
*i. For non-const iterators, a
38730
<!--span style="font-family: monospace;"-->
38731
value=() function is also provided which allows you to change the value
38732
pointed by the iterator. This is equivalent to the C++ construct of
38733
dereferencing and assignment, like
38734
<!--span style="font-family: monospace;"-->
38735
*i = something. </P>
38736
<P>Thus, given say a vector class of doubles defined as:</P>
38737
<DIV class="code" style="font-family: monospace;">
38738
<!--span class="code"-->
38739
%module doublevector
38741
<!--span class="code"-->
38742
<BR> %include std_vector.i
38744
<!--span class="code"-->
38745
<BR> %template(DoubleVector) std::vector<double>;</DIV>
38746
<P>Its iterator can then be used from Ruby like:</P>
38747
<DIV class="targetlang" style="font-family: monospace;">require
38749
<BR> include Doublevector
38751
<BR> v = DoubleVector.new
38757
<BR> # an elaborate and less efficient way of doing v.map! { |x| x+2 }
38762
<BR> val = i.value
38763
<BR> val += 2
38764
<BR> i.value = val
38769
<!--span style="font-weight: bold;"-->
38770
>> [3, 4, 5 ]</DIV>
38772
<P>If you'd rather have STL classes without any iterators, you should
38774
<!--span style="font-family: monospace;"-->
38775
-DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.</P>
38776
<H3><A name="Ruby_nn24"></A>30.3.16 C++ Smart Pointers</H3>
37088
38777
<P> In certain C++ programs, it is common to use classes that have been
37089
38778
wrapped by so-called "smart pointers." Generally, this involves the use
37090
38779
of a template class that implements <TT>operator->()</TT> like this:</P>
37562
39254
<P>Since SWIG's exception handling is user-definable, you are not
37563
39255
limited to C++ exception handling. See the chapter on <A href="#Customization">
37564
39256
Customization Features</A> for more examples.</P>
37565
<H3><A name="Ruby_nn35"></A>30.6.2 Raising exceptions</H3>
39257
<H3><A name="Ruby_nn34_2"></A>30.6.2 Handling Ruby Blocks</H3>
39258
<P>One of the highlights of Ruby and most of its standard library is the
39259
use of blocks, which allow the easy creation of continuations and other
39260
niceties. Blocks in ruby are also often used to simplify the passing
39261
of many arguments to a class.</P>
39262
<P>In order to make your class constructor support blocks, you can take
39263
advantage of the %exception directive, which will get run after the C++
39264
class' constructor was called. </P>
39265
<P>For example, this yields the class over after its construction:
39271
<BR> Window(int x, int y, int w, int h);
39272
<BR>// .... other methods here ....
39275
<BR>// Add support for yielding self in the Class' constructor.
39276
<BR>%exception Window::Window {
39278
<BR> if (rb_block_given_p()) {
39279
<BR> rb_yield(self);
39283
<P> Then, in ruby, it can be used like:</P>
39284
<DIV class="targetlang" style="font-family: monospace;">
39285
Window.new(0,0,360,480) { |w|
39286
<BR> w.color = Fltk::RED
39287
<BR> w.border = false
39289
<!--span class="targetlang"-->
39292
<P>For other methods, you can usually use a dummy parameter with a
39293
special in typemap, like:</P>
39294
<DIV class="code" style="font-family: monospace;">//
39295
<BR> // original function was:
39297
<BR> // void func(int x);
39299
<BR> %typemap(in,numinputs=0) int RUBY_YIELD_SELF {
39300
<BR> if ( !rb_block_given_p() )
39301
<BR> rb_raise("No block given");
39302
<BR> return rb_yield(self);
39306
<BR> void func(int x, int RUBY_YIELD_SELF );
39308
<P>For more information on typemaps, see <A href="#Ruby_nn37">Typemaps</A>
39310
<H3><A name="Ruby_nn35"></A>30.6.3 Raising exceptions</H3>
37566
39311
<P>There are three ways to raise exceptions from C++ code to Ruby.</P>
37567
39312
<P>The first way is to use <TT>SWIG_exception(int code, const char *msg)</TT>
37568
39313
. The following table shows the mappings from SWIG error codes to Ruby
37569
39314
exceptions:</P>
37570
<TABLE border="1" summary="Mapping between SWIG error codes and Ruby exceptions."
37572
<TR><TD>SWIG_MemoryError</TD><TD>rb_eNoMemError</TD></TR>
37573
<TR><TD>SWIG_IOError</TD><TD>rb_eIOError</TD></TR>
37574
<TR><TD>SWIG_RuntimeError</TD><TD>rb_eRuntimeError</TD></TR>
37575
<TR><TD>SWIG_IndexError</TD><TD>rb_eIndexError</TD></TR>
37576
<TR><TD>SWIG_TypeError</TD><TD>rb_eTypeError</TD></TR>
37577
<TR><TD>SWIG_DivisionByZero</TD><TD>rb_eZeroDivError</TD></TR>
37578
<TR><TD>SWIG_OverflowError</TD><TD>rb_eRangeError</TD></TR>
37579
<TR><TD>SWIG_SyntaxError</TD><TD>rb_eSyntaxError</TD></TR>
37580
<TR><TD>SWIG_ValueError</TD><TD>rb_eArgError</TD></TR>
37581
<TR><TD>SWIG_SystemError</TD><TD>rb_eFatal</TD></TR>
37582
<TR><TD>SWIG_AttributeError</TD><TD>rb_eRuntimeError</TD></TR>
37583
<TR><TD>SWIG_NullReferenceError</TD><TD>rb_eNullReferenceError*</TD></TR>
37584
<TR><TD>SWIG_ObjectPreviouslyDeletedError</TD><TD>
37585
rb_eObjectPreviouslyDeleted*</TD></TR>
37586
<TR><TD>SWIG_UnknownError</TD><TD>rb_eRuntimeError</TD></TR>
37587
<TR><TD colspan="2">* These error classes are created by SWIG and are
37588
not built-in Ruby exception classes</TD></TR>
39315
<DIV class="diagram">
39316
<TABLE border="1" class="diagram" summary="Mapping between SWIG error codes and Ruby exceptions."
39317
width="80%"><TBODY></TBODY>
39318
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39319
SWIG_MemoryError</DIV></TD><TD style="font-family: monospace;"><DIV>
39320
rb_eNoMemError</DIV></TD></TR>
39321
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39322
SWIG_IOError</DIV></TD><TD style="font-family: monospace;"><DIV>
39323
rb_eIOError</DIV></TD></TR>
39324
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39325
SWIG_RuntimeError</DIV></TD><TD style="font-family: monospace;"><DIV>
39326
rb_eRuntimeError</DIV></TD></TR>
39327
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39328
SWIG_IndexError</DIV></TD><TD style="font-family: monospace;"><DIV>
39329
rb_eIndexError</DIV></TD></TR>
39330
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39331
SWIG_TypeError</DIV></TD><TD style="font-family: monospace;"><DIV>
39332
rb_eTypeError</DIV></TD></TR>
39333
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39334
SWIG_DivisionByZero</DIV></TD><TD style="font-family: monospace;"><DIV>
39335
rb_eZeroDivError</DIV></TD></TR>
39336
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39337
SWIG_OverflowError</DIV></TD><TD style="font-family: monospace;"><DIV>
39338
rb_eRangeError</DIV></TD></TR>
39339
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39340
SWIG_SyntaxError</DIV></TD><TD style="font-family: monospace;"><DIV>
39341
rb_eSyntaxError</DIV></TD></TR>
39342
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39343
SWIG_ValueError</DIV></TD><TD style="font-family: monospace;"><DIV>
39344
rb_eArgError</DIV></TD></TR>
39345
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39346
SWIG_SystemError</DIV></TD><TD style="font-family: monospace;"><DIV>
39347
rb_eFatal</DIV></TD></TR>
39348
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39349
SWIG_AttributeError</DIV></TD><TD style="font-family: monospace;"><DIV>
39350
rb_eRuntimeError</DIV></TD></TR>
39351
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39352
SWIG_NullReferenceError</DIV></TD><TD style="font-family: monospace;"><DIV>
39353
rb_eNullReferenceError*</DIV></TD></TR>
39354
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39355
SWIG_ObjectPreviouslyDeletedError</DIV></TD><TD style="font-family: monospace;">
39356
<DIV>rb_eObjectPreviouslyDeleted*</DIV></TD></TR>
39357
<TR><TD class="diagram" style="font-family: monospace;"><DIV>
39358
SWIG_UnknownError</DIV></TD><TD style="font-family: monospace;"><DIV>
39359
rb_eRuntimeError</DIV></TD></TR>
39360
<TR class="diagram" style="font-family: monospace;"><TD colspan="2"><DIV>
39361
* These error classes are created by SWIG and are not built-in Ruby
39362
exception classes</DIV></TD></TR>
37590
39365
<P>The second way to raise errors is to use <TT>SWIG_Raise(obj, type,
37591
39366
desc)</TT>. Obj is a C++ instance of an exception class, type is a
37592
39367
string specifying the type of exception (for example, "MyError") and
37593
39368
desc is the SWIG description of the exception class. For example:</P>
37594
<P> %raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException,
37595
0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);</P>
39369
<DIV class="code" style="font-family: monospace;">
39370
%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0),
39371
":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);</DIV>
37596
39372
<P>This is useful when you want to pass the current exception object
37597
39373
directly to Ruby, particularly when the object is an instance of class
37598
39374
marked as an <TT>%exceptionclass</TT> (see the next section for more
37733
39545
<P> When a multi-argument typemap is defined, the arguments are always
37734
39546
handled as a single Ruby object. This allows the function <TT>count</TT>
37735
39547
to be used as follows (notice how the length parameter is omitted):</P>
39548
<DIV class="code targetlang">
37737
39549
<PRE>puts Example.count('o','Hello World')
37741
<H3><A name="Ruby_nn39"></A>30.7.2 Ruby typemaps</H3>
37742
<P> The previous section illustrated an "in" typemap for converting Ruby
37743
objects to C. A variety of different typemap methods are defined by the
37744
Ruby module. For example, to convert a C integer back into a Ruby
37745
object, you might define an "out" typemap like this:</P>
37747
<PRE>%typemap(out) int {
37748
<BR> $result = INT2NUM($1);
37752
<P> The following list details all of the typemap methods that can be
39553
<H3><A name="Ruby_Typemap_scope"></A>30.7.2 Typemap scope</H3>
39554
<P> Once defined, a typemap remains in effect for all of the
39555
declarations that follow. A typemap may be redefined for different
39556
sections of an input file. For example:</P>
39559
<BR>%typemap(in) int {
39563
<BR>int fact(int); // typemap1
39564
<BR>int gcd(int x, int y); // typemap1
39567
<BR>%typemap(in) int {
39571
<BR>int isprime(int); // typemap2
39574
<P> One exception to the typemap scoping rules pertains to the <TT>
39575
%extend</TT> declaration. <TT>%extend</TT> is used to attach new
39576
declarations to a class or structure definition. Because of this, all
39577
of the declarations in an <TT>%extend</TT> block are subject to the
39578
typemap rules that are in effect at the point where the class itself is
39579
defined. For example:</P>
39585
<BR>%typemap(in) int {
39590
<BR> int blah(int x); // typemap has no effect. Declaration is attached to Foo which
39591
<BR> // appears before the %typemap declaration.
39595
<H3><A name="Ruby_Copying_a_typemap"></A>30.7.3 Copying a typemap</H3>
39596
<P> A typemap is copied by using assignment. For example:</P>
39598
<PRE>%typemap(in) Integer = int;
39603
<PRE>%typemap(in) Integer, Number, int32_t = int;
39606
<P> Types are often managed by a collection of different typemaps. For
39609
<PRE>%typemap(in) int { ... }
39610
<BR>%typemap(out) int { ... }
39611
<BR>%typemap(varin) int { ... }
39612
<BR>%typemap(varout) int { ... }
39615
<P> To copy all of these typemaps to a new type, use <TT>%apply</TT>.
39618
<PRE>%apply int { Integer }; // Copy all int typemaps to Integer
39619
<BR>%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
39622
<P> The patterns for <TT>%apply</TT> follow the same rules as for <TT>
39623
%typemap</TT>. For example:</P>
39625
<PRE>%apply int *output { Integer *output }; // Typemap with name
39626
<BR>%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
39629
<H3><A name="Ruby_Deleting_a_typemap"></A>30.7.4 Deleting a typemap</H3>
39630
<P> A typemap can be deleted by simply defining no code. For example:</P>
39632
<PRE>%typemap(in) int; // Clears typemap for int
39633
<BR>%typemap(in) int, long, short; // Clears typemap for int, long, short
39634
<BR>%typemap(in) int *output;
39637
<P> The <TT>%clear</TT> directive clears all typemaps for a given type.
39640
<PRE>%clear int; // Removes all types for int
39641
<BR>%clear int *output, long *output;
39644
<P><B> Note:</B> Since SWIG's default behavior is defined by typemaps,
39645
clearing a fundamental type like <TT>int</TT> will make that type
39646
unusable unless you also define a new set of typemaps immediately after
39647
the clear operation.</P>
39648
<H3><A name="Ruby_Placement_of_typemaps"></A>30.7.5 Placement of
39650
<P> Typemap declarations can be declared in the global scope, within a
39651
C++ namespace, and within a C++ class. For example:</P>
39653
<PRE>%typemap(in) int {
39657
<BR>namespace std {
39659
<BR> %typemap(in) string {
39666
<BR> typedef const int & const_reference;
39667
<BR> %typemap(out) const_reference {
39673
<P> When a typemap appears inside a namespace or class, it stays in
39674
effect until the end of the SWIG input (just like before). However, the
39675
typemap takes the local scope into account. Therefore, this code</P>
39677
<PRE>namespace std {
39679
<BR> %typemap(in) string {
39685
<P> is really defining a typemap for the type <TT>std::string</TT>. You
39686
could have code like this:</P>
39688
<PRE>namespace std {
39690
<BR> %typemap(in) string { /* std::string */
39695
<BR>namespace Foo {
39697
<BR> %typemap(in) string { /* Foo::string */
39703
<P> In this case, there are two completely distinct typemaps that apply
39704
to two completely different types (<TT>std::string</TT> and <TT>
39705
Foo::string</TT>).</P>
39706
<P> It should be noted that for scoping to work, SWIG has to know that <TT>
39707
string</TT> is a typename defined within a particular namespace. In this
39708
example, this is done using the class declaration <TT>class string</TT>
39710
<H3><A name="Ruby_nn39"></A>30.7.6 Ruby typemaps</H3>
39711
<P>The following list details all of the typemap methods that can be
37753
39712
used by the Ruby module:</P>
37754
<P><TT>%typemap(in)</TT></P>
37755
<DIV class="indent">Converts Ruby objects to input function arguments</DIV>
37756
<P><TT>%typemap(out)</TT></P>
37757
<DIV class="indent">Converts return value of a C function to a Ruby
37759
<P><TT>%typemap(varin)</TT></P>
37760
<DIV class="indent">Assigns a C global variable from a Ruby object</DIV>
37761
<P><TT>%typemap(varout)</TT></P>
37762
<DIV class="indent">Returns a C global variable as a Ruby object</DIV>
37763
<P><TT>%typemap(freearg)</TT></P>
37764
<DIV class="indent">Cleans up a function argument (if necessary)</DIV>
37765
<P><TT>%typemap(argout)</TT></P>
37766
<DIV class="indent">Output argument processing</DIV>
37767
<P><TT>%typemap(ret)</TT></P>
37768
<DIV class="indent">Cleanup of function return values</DIV>
37769
<P><TT>%typemap(memberin)</TT></P>
37770
<DIV class="indent">Setting of structure/class member data</DIV>
37771
<P><TT>%typemap(globalin)</TT></P>
37772
<DIV class="indent">Setting of C global variables</DIV>
37773
<P><TT>%typemap(check)</TT></P>
37774
<DIV class="indent">Checks function input values.</DIV>
37775
<P><TT>%typemap(default)</TT></P>
37776
<DIV class="indent">Set a default value for an argument (making it
37778
<P><TT>%typemap(arginit)</TT></P>
37779
<DIV class="indent">Initialize an argument to a value before any
37780
conversions occur.</DIV>
37781
<P> Examples of these typemaps appears in the <A href="#ruby_typemap_examples">
37782
section on typemap examples</A></P>
37783
<H3><A name="Ruby_nn40"></A>30.7.3 Typemap variables</H3>
37784
Within a typemap, a number of special variables prefaced with a <TT>$</TT>
37785
may appear. A full list of variables can be found in the "<A href="#Typemaps">
37786
Typemaps</A>" chapter. This is a list of the most common variables:
39713
<H4><A name="Ruby_in_typemap"></A>30.7.6.1 "in" typemap</H4>
39714
<P>Converts Ruby objects to input function arguments. For example:</P>
39716
<PRE>%typemap(in) int {
39717
<BR> $1 = NUM2INT($input);
39721
<P> The following special variables are available:</P>
39722
<DIV class="diagram">
39723
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - in typemap"
39724
width="100%"><TBODY></TBODY>
39725
<TR><TD style="font-family: monospace;">$input</TD><TD style="font-family: monospace;">
39726
Input object holding value to be converted.</TD></TR>
39727
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
39728
Name of function/method being wrapped</TD></TR>
39729
<TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
39730
Argument being sent to the function</TD></TR>
39731
<TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
39732
Name of the argument (if provided)</TD></TR>
39733
<TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
39734
The actual C datatype matched by the typemap.</TD></TR>
39735
<TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
39736
The assignable version of the C datatype matched by the typemap.</TD></TR>
39739
<P> This is probably the most commonly redefined typemap because it can
39740
be used to implement customized conversions.</P>
39741
<P> In addition, the "in" typemap allows the number of converted
39742
arguments to be specified. For example:</P>
39744
<PRE>// Ignored argument.
39745
<BR>%typemap(in, numinputs=0) int *out (int temp) {
39746
<BR> $1 = &temp;
39750
<P> At this time, only zero or one arguments may be converted.</P>
39751
<H4><A name="Ruby_typecheck_typemap"></A>30.7.6.2 "typecheck" typemap</H4>
39752
<P> The "typecheck" typemap is used to support overloaded functions and
39753
methods. It merely checks an argument to see whether or not it matches
39754
a specific type. For example:</P>
39756
<PRE>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
39757
<BR> $1 = FIXNUM_P($input) ? 1 : 0;
39761
<P> For typechecking, the $1 variable is always a simple integer that is
39762
set to 1 or 0 depending on whether or not the input argument is the
39764
<P> If you define new "in" typemaps<EM> and</EM> your program uses
39765
overloaded methods, you should also define a collection of "typecheck"
39766
typemaps. More details about this follow in a later section on
39767
"Typemaps and Overloading."</P>
39768
<H4><A name="Ruby_out_typemap"></A>30.7.6.3 "out" typemap</H4>
39769
<P>Converts return value of a C function to a Ruby object.</P>
39770
<DIV class="code"><TT>
39771
<BR> %typemap(out) int {
39772
<BR> $result = INT2NUM( $1 );
39775
<P> The following special variables are available.</P>
39776
<DIV class="diagram">
39777
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - out typemap"
39778
width="100%"><TBODY></TBODY>
39779
<TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
39780
Result object returned to target language.</TD></TR>
39781
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
39782
Name of function/method being wrapped</TD></TR>
39783
<TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
39784
Argument being wrapped</TD></TR>
39785
<TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
39786
Name of the argument (if provided)</TD></TR>
39787
<TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
39788
The actual C datatype matched by the typemap.</TD></TR>
39789
<TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
39790
The assignable version of the C datatype matched by the typemap.</TD></TR>
39794
<H4><A name="Ruby_arginit_typemap"></A>30.7.6.4 "arginit" typemap</H4>
39795
<P> The "arginit" typemap is used to set the initial value of a function
39796
argument--before any conversion has occurred. This is not normally
39797
necessary, but might be useful in highly specialized applications. For
39800
<PRE>// Set argument to NULL before any conversion occurs
39801
<BR>%typemap(arginit) int *data {
39806
<H4><A name="Ruby_default_typemap"></A>30.7.6.5 "default" typemap</H4>
39807
<P> The "default" typemap is used to turn an argument into a default
39808
argument. For example:</P>
39810
<PRE>%typemap(default) int flags {
39811
<BR> $1 = DEFAULT_FLAGS;
39814
<BR>int foo(int x, int y, int flags);
39817
<P> The primary use of this typemap is to either change the wrapping of
39818
default arguments or specify a default argument in a language where
39819
they aren't supported (like C). Target languages that do not support
39820
optional arguments, such as Java and C#, effectively ignore the value
39821
specified by this typemap as all arguments must be given.</P>
39822
<P> Once a default typemap has been applied to an argument, all
39823
arguments that follow must have default values. See the <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#SWIG_default_args">
39824
Default/optional arguments</A> section for further information on
39825
default argument wrapping.</P>
39826
<H4><A name="Ruby_check_typemap"></A>30.7.6.6 "check" typemap</H4>
39827
<P> The "check" typemap is used to supply value checking code during
39828
argument conversion. The typemap is applied<EM> after</EM> arguments
39829
have been converted. For example:</P>
39831
<PRE>%typemap(check) int positive {
39832
<BR> if ($1 <= 0) {
39833
<BR> SWIG_exception(SWIG_ValueError,"Expected positive value.");
39838
<H4><A name="Ruby_argout_typemap_"></A>30.7.6.7 "argout" typemap</H4>
39839
<P> The "argout" typemap is used to return values from arguments. This
39840
is most commonly used to write wrappers for C/C++ functions that need
39841
to return multiple values. The "argout" typemap is almost always
39842
combined with an "in" typemap---possibly to ignore the input value. For
39845
<PRE>/* Set the input argument to point to a temporary variable */
39846
<BR>%typemap(in, numinputs=0) int *out (int temp) {
39847
<BR> $1 = &temp;
39850
<BR>%typemap(argout, fragment="output_helper") int *out {
39851
<BR> // Append output value $1 to $result (assuming a single integer in this case)
39852
<BR> $result = output_helper( $result, INT2NUM(*$1) );
39856
<P> The following special variables are available.</P>
39857
<DIV class="diagram">
39858
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - argout typemap"
39859
width="100%"><TBODY></TBODY>
39860
<TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
39861
Result object returned to target language.</TD></TR>
39862
<TR><TD style="font-family: monospace;">$input</TD><TD style="font-family: monospace;">
39863
The original input object passed.</TD></TR>
39864
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
39865
Name of function/method being wrapped.</TD></TR>
39868
<P> The code supplied to the "argout" typemap is always placed after the
39869
"out" typemap. If multiple return values are used, the extra return
39870
values are often appended to return value of the function.</P>
39871
<P>Output helper is a fragment that usually defines a macro to some
39872
function like SWIG_Ruby_AppendOutput.</P>
39873
<P> See the <TT>typemaps.i</TT> library for examples.</P>
39874
<H4><A name="Ruby_freearg_typemap_"></A>30.7.6.8 "freearg" typemap</H4>
39875
<P> The "freearg" typemap is used to cleanup argument data. It is only
39876
used when an argument might have allocated resources that need to be
39877
cleaned up when the wrapper function exits. The "freearg" typemap
39878
usually cleans up argument resources allocated by the "in" typemap. For
39881
<PRE>// Get a list of integers
39882
<BR>%typemap(in) int *items {
39883
<BR> int nitems = Length($input);
39884
<BR> $1 = (int *) malloc(sizeof(int)*nitems);
39886
<BR>// Free the list
39887
<BR>%typemap(freearg) int *items {
39892
<P> The "freearg" typemap inserted at the end of the wrapper function,
39893
just before control is returned back to the target language. This code
39894
is also placed into a special variable <TT>$cleanup</TT> that may be
39895
used in other typemaps whenever a wrapper function needs to abort
39897
<H4><A name="Ruby_newfree_typemap"></A>30.7.6.9 "newfree" typemap</H4>
39898
<P> The "newfree" typemap is used in conjunction with the <TT>%newobject</TT>
39899
directive and is used to deallocate memory used by the return result of
39900
a function. For example:</P>
39902
<PRE>%typemap(newfree) string * {
39905
<BR>%typemap(out) string * {
39906
<BR> $result = PyString_FromString($1->c_str());
39910
<BR>%newobject foo;
39915
<P> See <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#ownership">
39916
Object ownership and %newobject</A> for further details.</P>
39917
<H4><A name="Ruby_memberin_typemap"></A>30.7.6.10 "memberin" typemap</H4>
39918
<P> The "memberin" typemap is used to copy data from<EM> an already
39919
converted input value</EM> into a structure member. It is typically
39920
used to handle array members and other special cases. For example:</P>
39922
<PRE>%typemap(memberin) int [4] {
39923
<BR> memmove($1, $input, 4*sizeof(int));
39927
<P> It is rarely necessary to write "memberin" typemaps---SWIG already
39928
provides a default implementation for arrays, strings, and other
39930
<H4><A name="Ruby_varin_typemap"></A>30.7.6.11 "varin" typemap</H4>
39931
<P> The "varin" typemap is used to convert objects in the target
39932
language to C for the purposes of assigning to a C/C++ global variable.
39933
This is implementation specific.</P>
39934
<H4><A name="Ruby_varout_typemap_"></A>30.7.6.12 "varout" typemap</H4>
39935
<P> The "varout" typemap is used to convert a C/C++ object to an object
39936
in the target language when reading a C/C++ global variable. This is
39937
implementation specific.</P>
39938
<H4><A name="Ruby_throws_typemap"></A>30.7.6.13 "throws" typemap</H4>
39939
<P> The "throws" typemap is only used when SWIG parses a C++ method with
39940
an exception specification or has the <TT>%catches</TT> feature
39941
attached to the method. It provides a default mechanism for handling
39942
C++ methods that have declared the exceptions they will throw. The
39943
purpose of this typemap is to convert a C++ exception into an error or
39944
exception in the target language. It is slightly different to the other
39945
typemaps as it is based around the exception type rather than the type
39946
of a parameter or variable. For example:</P>
39948
<PRE>%typemap(throws) const char * %{
39949
<BR> rb_raise(rb_eRuntimeError, $1);
39952
<BR>void bar() throw (const char *);
39955
<P> As can be seen from the generated code below, SWIG generates an
39956
exception handler with the catch block comprising the "throws" typemap
39963
<BR>catch(char const *_e) {
39964
<BR> rb_raise(rb_eRuntimeError, _e);
39970
<P> Note that if your methods do not have an exception specification yet
39971
they do throw exceptions, SWIG cannot know how to deal with them. For a
39972
neat way to handle these, see the <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#exception">
39973
Exception handling with %exception</A> section.</P>
39974
<H4><A name="Ruby_directorin_typemap"></A>30.7.6.14 directorin typemap</H4>
39975
<P>Converts C++ objects in director member functions to ruby objects. It
39976
is roughly the opposite of the "in" typemap, making its typemap rule
39977
often similar to the "out" typemap.</P>
39978
<DIV class="code"><TT>
39979
<BR> %typemap(directorin) int {
39980
<BR> $result = INT2NUM($1);
39983
<P> The following special variables are available.</P>
39984
<DIV class="diagram">
39985
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorin typemap"
39986
width="100%"><TBODY></TBODY>
39987
<TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
39988
Result object returned to target language.</TD></TR>
39989
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
39990
Name of function/method being wrapped</TD></TR>
39991
<TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
39992
Argument being wrapped</TD></TR>
39993
<TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
39994
Name of the argument (if provided)</TD></TR>
39995
<TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
39996
The actual C datatype matched by the typemap.</TD></TR>
39997
<TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
39998
The assignable version of the C datatype matched by the typemap.</TD></TR>
39999
<TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
40000
C++ this, referring to the class itself.</TD></TR>
40003
<H4><A name="Ruby_directorout_typemap"></A>30.7.6.15 directorout typemap</H4>
40004
<P>Converts Ruby objects in director member functions to C++ objects.
40005
It is roughly the opposite of the "out" typemap, making its rule often
40006
similar to the "in" typemap.</P>
40007
<DIV class="code"><TT style="font-family: monospace;">
40008
<BR> %typemap(directorout) int {</TT><TT>
40009
<BR> $result = NUM2INT($1);</TT>
40010
<BR> <TT style="font-family: monospace;">}
40012
<P> The following special variables are available:</P>
40013
<DIV class="diagram">
40014
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorout typemap"
40015
width="100%"><TBODY></TBODY>
40016
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
40017
Name of function/method being wrapped</TD></TR>
40018
<TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
40019
Argument being sent to the function</TD></TR>
40020
<TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
40021
Name of the argument (if provided)</TD></TR>
40022
<TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
40023
The actual C datatype matched by the typemap.</TD></TR>
40024
<TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
40025
The assignable version of the C datatype matched by the typemap.</TD></TR>
40026
<TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
40027
C++ this, referring to the class itself.</TD></TR>
40030
<P>Currently, the directorout nor the out typemap support the option
40031
<!--span style="font-family: monospace;"-->
40032
numoutputs, but the Ruby module provides that functionality through a
40033
%feature directive. Thus, a function can be made to return "nothing"
40035
<DIV class="code" style="font-family: monospace;">
40036
%feature("numoutputs","0") MyClass::function;</DIV>
40037
<P>This feature can be useful if a function returns a status code, which
40038
you want to discard but still use the typemap to raise an exception.
40040
<H4><A name="Ruby_directorargout_typemap"></A>30.7.6.16 directorargout
40042
<P>Output argument processing in director member functions.</P>
40043
<DIV class="code"><TT style="font-family: monospace;">
40044
%typemap(directorargout, fragment="output_helper") int {</TT><TT>
40045
<BR> $result = output_helper( $result, NUM2INT($1) );</TT>
40046
<BR> <TT style="font-family: monospace;">}</TT></DIV>
40047
<P> The following special variables are available:</P>
40048
<DIV class="diagram">
40049
<TABLE border="1" cellpadding="2" cellspacing="2" style="text-align: left; width: 100%;"
40050
summary="Special variables - directorargout typemap"><TBODY></TBODY>
40051
<TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
40052
Result that the director function returns</TD></TR>
40053
<TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
40054
name of the function/method being wrapped</TD></TR>
40055
<TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
40056
Argument being sent to the function</TD></TR>
40057
<TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
40058
Name of the argument (if provided)</TD></TR>
40059
<TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
40060
The actual C datatype matched by the typemap</TD></TR>
40061
<TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
40062
The assignable version of the C datatype matched by the typemap</TD></TR>
40063
<TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
40064
C++ this, referring to the instance of the class itself</TD></TR>
40067
<H4><A name="Ruby_ret_typemap"></A>30.7.6.17 ret typemap</H4>
40068
<P>Cleanup of function return values</P>
40069
<H4><A name="Ruby_globalin_typemap"></A>30.7.6.18 globalin typemap</H4>
40070
<P>Setting of C global variables</P>
40071
<H3><A name="Ruby_nn40"></A>30.7.7 Typemap variables</H3>
40072
<P> Within a typemap, a number of special variables prefaced with a <TT>
40073
$</TT> may appear. A full list of variables can be found in the "<A href="#Typemaps">
40074
Typemaps</A>" chapter. This is a list of the most common variables:</P>
37787
40075
<P><TT>$1</TT></P>
37788
40076
<DIV class="indent">A C local variable corresponding to the actual type
37789
40077
specified in the <TT>%typemap</TT> directive. For input values, this is
37809
40097
be properly assigned.</DIV>
37810
40098
<P><TT>$symname</TT></P>
37811
40099
<DIV class="indent">The Ruby name of the wrapper function being created.</DIV>
37812
<H3><A name="Ruby_nn41"></A>30.7.4 Useful Functions</H3>
40100
<H3><A name="Ruby_nn41"></A>30.7.8 Useful Functions</H3>
37813
40101
<P> When you write a typemap, you usually have to work directly with
37814
40102
Ruby objects. The following functions may prove to be useful. (These
37815
40103
functions plus many more can be found in <A href="http://www.rubycentral.com/book">
37816
<EM>Programming Ruby</EM></A>, by David Thomas and Andrew Hunt.)</P>
37818
<H4><A name="Ruby_nn42"></A>30.7.4.1 C Datatypes to Ruby Objects</H4>
37820
<PRE>INT2NUM(long or int) - int to Fixnum or Bignum
37821
<BR>INT2FIX(long or int) - int to Fixnum (faster than INT2NUM)
37822
<BR>CHR2FIX(char) - char to Fixnum
37823
<BR>rb_str_new2(char*) - char* to String
37824
<BR>rb_float_new(double) - double to Float
40104
<EM>Programming Ruby</EM></A>, by David Thomas and Andrew Hunt.) </P>
40105
<P>In addition, we list equivalent functions that Swig defines, which
40106
provide a language neutral conversion (these functions are defined for
40107
each swig language supported). If you are trying to create a swig file
40108
that will work under multiple languages, it is recommended you stick to
40109
the swig functions instead of the native Ruby functions. That should
40110
help you avoid having to rewrite a lot of typemaps across multiple
40112
<H4><A name="Ruby_nn42"></A>30.7.8.1 C Datatypes to Ruby Objects</H4>
40113
<DIV class="diagram">
40114
<TABLE border="1" cellpadding="2" cellspacing="2" style="width: 100%;" summary="Datatypes">
40116
<TR><TH style="font-weight: bold;">RUBY</TH><TH style="font-weight: bold;">
40117
Swig</TH><TD></TD></TR>
40118
<TR><TD style="font-family: monospace;">INT2NUM(long or int)</TD><TD style="font-family: monospace;">
40119
SWIG_From_int(int x)</TD><TD> int to Fixnum or Bignum</TD></TR>
40120
<TR><TD style="font-family: monospace;">INT2FIX(long or int)</TD><TD style="font-family: monospace;">
40121
</TD><TD> int to Fixnum (faster than INT2NUM)</TD></TR>
40122
<TR><TD style="font-family: monospace;">CHR2FIX(char)</TD><TD style="font-family: monospace;">
40123
SWIG_From_char(char x)</TD><TD> char to Fixnum</TD></TR>
40124
<TR><TD style="font-family: monospace;">rb_str_new2(char*)</TD><TD style="font-family: monospace;">
40125
SWIG_FromCharPtrAndSize(char*, size_t)</TD><TD> char* to String</TD></TR>
40126
<TR><TD style="font-family: monospace;">rb_float_new(double)</TD><TD style="font-family: monospace;">
40127
SWIG_From_double(double),
40128
<BR> SWIG_From_float(float)</TD><TD>float/double to Float</TD></TR>
37827
<H4><A name="Ruby_nn43"></A>30.7.4.2 Ruby Objects to C Datatypes</H4>
37829
<PRE> int NUM2INT(Numeric)
37830
<BR> int FIX2INT(Numeric)
37831
<BR> unsigned int NUM2UINT(Numeric)
37832
<BR> unsigned int FIX2UINT(Numeric)
37833
<BR> long NUM2LONG(Numeric)
37834
<BR> long FIX2LONG(Numeric)
37835
<BR>unsigned long FIX2ULONG(Numeric)
37836
<BR> char NUM2CHR(Numeric or String)
37837
<BR> char * STR2CSTR(String)
37838
<BR> char * rb_str2cstr(String, int*length)
37839
<BR> double NUM2DBL(Numeric)
40131
<H4><A name="Ruby_nn43"></A>30.7.8.2 Ruby Objects to C Datatypes</H4>
40132
<P>Here, while the Ruby versions return the value directly, the SWIG
40133
versions do not, but return a status value to indicate success (
40134
<!--span style="font-family: monospace;"-->
40135
SWIG_OK). While more akward to use, this allows you to write typemaps
40136
that report more helpful error messages, like:</P>
40137
<DIV class="code" style="font-family: monospace;">
40138
<BR> %typemap(in) size_t (int ok)
40140
<BR> ok = SWIG_AsVal_size_t($input, &$1);
40141
<BR> if (!SWIG_IsOK(ok)) {
40142
<BR> SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError(
40143
"$1_name", "$1_type","$symname", $argnum, $input ));
40144
<BR> }
40146
<BR> }</DIV><DIV style="font-family: monospace;"> </DIV><DIV class="diagram">
40147
<TABLE border="1" cellpadding="2" cellspacing="2" summary="Ruby objects" width="100%">
40149
<TR><TD style="font-family: monospace;">int NUM2INT(Numeric)</TD><TD style="font-family: monospace;">
40150
SWIG_AsVal_int(VALUE, int*)</TD></TR>
40151
<TR><TD style="font-family: monospace;">int FIX2INT(Numeric)</TD><TD style="font-family: monospace;">
40152
SWIG_AsVal_int(VALUE, int*)</TD></TR>
40153
<TR><TD style="font-family: monospace;">unsigned int NUM2UINT(Numeric)</TD><TD
40154
style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</TD>
40156
<TR><TD style="font-family: monospace;">unsigned int FIX2UINT(Numeric)</TD><TD
40157
style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</TD>
40159
<TR><TD style="font-family: monospace;">long NUM2LONG(Numeric)</TD><TD style="font-family: monospace;">
40160
SWIG_AsVal_long(VALUE, long*)</TD></TR>
40161
<TR><TD style="font-family: monospace;">long FIX2LONG(Numeric)</TD><TD style="font-family: monospace;">
40162
SWIG_AsVal_long(VALUE, long*)</TD></TR>
40163
<TR><TD style="font-family: monospace;">unsigned long FIX2ULONG(Numeric)</TD><TD
40164
style="font-family: monospace;">SWIG_AsVal_unsigned_SS_long(VALUE,
40165
unsigned long*)</TD></TR>
40166
<TR><TD style="font-family: monospace;">char NUM2CHR(Numeric or String)</TD><TD
40167
style="font-family: monospace;">SWIG_AsVal_char(VALUE, int*)</TD></TR>
40168
<TR><TD style="font-family: monospace;">char * STR2CSTR(String)</TD><TD style="font-family: monospace;">
40169
SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)</TD></TR>
40170
<TR><TD style="font-family: monospace;">char * rb_str2cstr(String,
40171
int*length)</TD><TD style="font-family: monospace;"></TD></TR>
40172
<TR><TD style="font-family: monospace;">double NUM2DBL(Numeric)</TD><TD style="font-family: monospace;">
40173
(double) SWIG_AsVal_int(VALUE) or similar</TD></TR>
37843
<H4><A name="Ruby_nn44"></A>30.7.4.3 Macros for VALUE</H4>
37844
<P> <TT>RSTRING(str)->len</TT></P>
40176
<H4><A name="Ruby_nn44"></A>30.7.8.3 Macros for VALUE</H4>
40177
<P> <TT>RSTRING_LEN(str)</TT></P>
37845
40178
<DIV class="indent">length of the Ruby string</DIV>
37846
<P><TT>RSTRING(str)->ptr</TT></P>
40179
<P><TT>RSTRING_PTR(str)</TT></P>
37847
40180
<DIV class="indent">pointer to string storage</DIV>
37848
<P><TT>RARRAY(arr)->len</TT></P>
40181
<P><TT>RARRAY_LEN(arr)</TT></P>
37849
40182
<DIV class="indent">length of the Ruby array</DIV>
37850
40183
<P><TT>RARRAY(arr)->capa</TT></P>
37851
40184
<DIV class="indent">capacity of the Ruby array</DIV>
37852
<P><TT>RARRAY(arr)->ptr</TT></P>
40185
<P><TT>RARRAY_PTR(arr)</TT></P>
37853
40186
<DIV class="indent">pointer to array storage</DIV>
37854
<H4><A name="Ruby_nn45"></A>30.7.4.4 Exceptions</H4>
40187
<H4><A name="Ruby_nn45"></A>30.7.8.4 Exceptions</H4>
37855
40188
<P> <TT>void rb_raise(VALUE exception, const char *fmt, ...)</TT></P>
37856
40189
<DIV class="indent"> Raises an exception. The given format string<I> fmt</I>
37857
40190
and remaining arguments are interpreted as with <TT>printf()</TT>.</DIV>
38327
<H2><A name="Ruby_nn53"></A>30.8 Advanced Topics</H2>
38328
<H3><A name="Ruby_nn54"></A>30.8.1 Operator overloading</H3>
40659
<BR> Note that this is mostly an example of typemaps. If you want to use
40660
the STL with ruby, you are advised to use the standard swig STL
40661
library, which does much more than this. Refer to the section called
40662
the<A href="#Ruby_nn23_1"> C++ Standard Template Library</A>.
40664
<H2><A name="Ruby_nn65"></A>30.8 Docstring Features</H2>
40665
<P> Using ri and rdoc web pages in Ruby libraries is a common practice.
40666
Given the way that SWIG generates the extensions by default, your users
40667
will normally not get any documentation for it, even if they run 'rdoc'
40668
on the resulting .c or .cxx file.</P>
40669
<P>The features described in this section make it easy for you to add
40670
rdoc strings to your modules, functions and methods that can then be
40671
read by Ruby's rdoc tool to generate html web pages, ri documentation,
40672
Windows chm file and an .xml description.</P>
40673
<P>rdoc can then be run from a console or shell window on a swig
40674
generated file. </P>
40675
<P>For example, to generate html web pages from a C++ file, you'd do: </P>
40676
<DIV class="code shell">
40677
<!--span style="font-family: monospace; font-weight: bold;"-->
40678
$ rdoc -E cxx=c -f html file_wrap.cxx</DIV>
40679
<P>To generate ri documentation from a c wrap file, you could do:</P>
40680
<DIV class="code shell">
40681
<!--span style="font-family: monospace; font-weight: bold;"-->
40682
$ rdoc -r file_wrap.c</DIV>
40683
<H3><A name="Ruby_nn66"></A>30.8.1 Module docstring</H3>
40684
<P> Ruby allows a docstring at the beginning of the file before any
40685
other statements, and it is typically used to give a general
40686
description of the entire module. SWIG supports this by setting an
40687
option of the <TT>%module</TT> directive. For example:</P>
40689
<PRE>%module(docstring="This is the example module's docstring") example
40692
<P> When you have more than just a line or so then you can retain the
40693
easy readability of the <TT>%module</TT> directive by using a macro.
40696
<PRE>%define DOCSTRING
40697
<BR>"The `XmlResource` class allows program resources defining menus,
40698
<BR>layout of controls on a panel, etc. to be loaded from an XML file."
40701
<BR>%module(docstring=DOCSTRING) xrc
40704
<H3><A name="Ruby_nn67"></A>30.8.2 %feature("autodoc")</H3>
40705
<P>Since SWIG does know everything about the function it wraps, it is
40706
possible to generate an rdoc containing the parameter types, names and
40707
default values. Since Ruby ships with one of the best documentation
40708
systems of any language, it makes sense to take advantage of it.</P>
40709
<P>SWIG's Ruby module provides support for the "autodoc" feature, which
40710
when attached to a node in the parse tree will cause an rdoc comment to
40711
be generated in the wrapper file that includes the name of the
40712
function, parameter names, default values if any, and return type if
40713
any. There are also several options for autodoc controlled by the value
40714
given to the feature, described below.</P>
40715
<H4><A name="Ruby_nn68"></A>30.8.2.1 %feature("autodoc", "0")</H4>
40716
<P> When the "0" option is given then the types of the parameters will<EM>
40717
not</EM> be included in the autodoc string. For example, given this
40718
function prototype:</P>
40720
<PRE>%feature("autodoc", "0");
40721
<BR>bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
40724
<P> Then Ruby code like this will be generated:</P>
40725
<DIV class="targetlang">
40726
<PRE>function_name(x, y, foo=nil, bar=nil) -> bool
40730
<H4><A name="Ruby_autodoc1"></A>30.8.2.2 %feature("autodoc", "1")</H4>
40731
<P> When the "1" option is used then the parameter types<EM> will</EM>
40732
be used in the rdoc string. In addition, an attempt is made to simplify
40733
the type name such that it makes more sense to the Ruby user. Pointer,
40734
reference and const info is removed, <TT>%rename</TT>'s are evaluated,
40735
etc. (This is not always successful, but works most of the time. See
40736
the next section for what to do when it doesn't.) Given the example
40737
above, then turning on the parameter types with the "1" option will
40738
result in rdoc code like this:</P>
40739
<DIV class="targetlang">
40740
<PRE>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
40744
<H4><A name="Ruby_autodoc2"></A>30.8.2.3 %feature("autodoc", "2")</H4>
40745
<P> When the "2" option is used then the parameter types will not be
40746
used in the rdoc string. However, they will be listed in full after the
40747
function. Given the example above, then turning on the parameter types
40748
with the "2" option will result in Ruby code like this:</P>
40749
<H4><A name="Ruby_feature_autodoc3"></A>30.8.2.4 %feature("autodoc",
40750
"3")</H4>
40751
<P> When the "3" option is used then the function will be documented
40752
using a combination of "1" and "2" above. Given the example above,
40753
then turning on the parameter types with the "2" option will result in
40754
Ruby code like this:</P>
40755
<DIV class="targetlang">
40756
<PRE>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
40765
<H4><A name="Ruby_nn70"></A>30.8.2.5 %feature("autodoc", "docstring")</H4>
40766
<P> Finally, there are times when the automatically generated autodoc
40767
string will make no sense for a Ruby programmer, particularly when a
40768
typemap is involved. So if you give an explicit value for the autodoc
40769
feature then that string will be used in place of the automatically
40770
generated string. For example:</P>
40772
<PRE>%feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
40773
<BR>void GetPosition(int* OUTPUT, int* OUTPUT);
40776
<H3><A name="Ruby_nn71"></A>30.8.3 %feature("docstring")</H3>
40777
<P> In addition to the autodoc strings described above, you can also
40778
attach any arbitrary descriptive text to a node in the parse tree with
40779
the "docstring" feature. When the proxy module is generated then any
40780
docstring associated with classes, function or methods are output. If
40781
an item already has an autodoc string then it is combined with the
40782
docstring and they are output together.</P>
40783
<H2><A name="Ruby_nn53"></A>30.9 Advanced Topics</H2>
40784
<H3><A name="Ruby_nn54"></A>30.9.1 Operator overloading</H3>
38329
40785
<P> SWIG allows operator overloading with, by using the <TT>%extend</TT>
38330
40786
or <TT>%rename</TT> commands in SWIG and the following operator names
38331
40787
(derived from Python):</P>
38333
<PRE><B> General</B>
38334
<BR>__repr__ - inspect
38336
<BR>__cmp__ - <=>
38337
<BR>__hash__ - hash
38338
<BR>__nonzero__ - nonzero?
38340
<BR><B> Callable</B>
38341
<BR>__call__ - call
38343
<BR><B> Collection</B>
38344
<BR>__len__ - length
38345
<BR>__getitem__ - []
38346
<BR>__setitem__ - []=
38348
<BR><B> Numeric</B>
38354
<BR>__divmod__ - divmod
38356
<BR>__lshift__ - <<
38357
<BR>__rshift__ - >>
38358
<BR>__and__ - &
38366
<BR>__float__ - to_f
38367
<BR>__coerce__ - coerce
38369
<BR><B>Additions in 1.3.13 </B>
40788
<DIV class="code diagram">
40789
<TABLE border="1" cellpadding="2" cellspacing="2" style="width: 100%; font-family: monospace;"
40790
summary="operator names"><TBODY></TBODY>
40791
<TR><TD><B> General</B></TD></TR>
40792
<TR><TD>__repr__</TD><TD> inspect</TD></TR>
40793
<TR><TD>__str__</TD><TD> to_s</TD></TR>
40794
<TR><TD>__cmp__</TD><TD> <=></TD></TR>
40795
<TR><TD>__hash__</TD><TD> hash</TD></TR>
40796
<TR><TD>__nonzero__</TD><TD> nonzero?</TD></TR>
40798
<TR><TD><B> Callable</B></TD></TR>
40799
<TR><TD>__call__</TD><TD> call</TD></TR>
40801
<TR><TD><B> Collection</B></TD></TR>
40802
<TR><TD>__len__</TD><TD> length</TD></TR>
40803
<TR><TD>__getitem__</TD><TD> []</TD></TR>
40804
<TR><TD>__setitem__</TD><TD> []=</TD></TR>
40806
<TR><TD><B> Numeric</B></TD></TR>
40807
<TR><TD>__add__</TD><TD> +</TD></TR>
40808
<TR><TD>__sub__</TD><TD> -</TD><TD></TD></TR>
40809
<TR><TD>__mul__</TD><TD> *</TD></TR>
40810
<TR><TD>__div__</TD><TD> /</TD></TR>
40811
<TR><TD>__mod__</TD><TD> %</TD></TR>
40812
<TR><TD>__divmod__</TD><TD> divmod</TD></TR>
40813
<TR><TD>__pow__</TD><TD> **</TD></TR>
40814
<TR><TD>__lshift__</TD><TD> <<</TD></TR>
40815
<TR><TD>__rshift__</TD><TD> >></TD></TR>
40816
<TR><TD>__and__</TD><TD> &</TD></TR>
40817
<TR><TD>__xor__</TD><TD> ^</TD></TR>
40818
<TR><TD>__or__</TD><TD> |</TD></TR>
40819
<TR><TD>__neg__</TD><TD> -@</TD><TD></TD></TR>
40820
<TR><TD>__pos__</TD><TD> +@</TD></TR>
40821
<TR><TD>__abs__</TD><TD> abs</TD></TR>
40822
<TR><TD>__invert__</TD><TD> ~</TD></TR>
40823
<TR><TD>__int__</TD><TD> to_i</TD></TR>
40824
<TR><TD>__float__</TD><TD> to_f</TD></TR>
40825
<TR><TD>__coerce__</TD><TD> coerce</TD></TR>
40827
<TR><TD><B>Additions in 1.3.13</B></TD></TR>
40828
<TR><TD>__lt__</TD><TD> <</TD></TR>
40829
<TR><TD>__le__</TD><TD> <=</TD></TR>
40830
<TR><TD>__eq__</TD><TD> ==</TD></TR>
40831
<TR><TD>__gt__</TD><TD> ></TD></TR>
40832
<TR><TD>__ge__</TD><TD> >=</TD></TR>
38378
40835
<P> Note that although SWIG supports the <TT>__eq__</TT> magic method
38379
40836
name for defining an equivalence operator, there is no separate method
38380
40837
for handling<I> inequality</I> since Ruby parses the expression<I> a !=
38381
40838
b</I> as<I> !(a == b)</I>.</P>
38382
<H3><A name="Ruby_nn55"></A>30.8.2 Creating Multi-Module Packages</H3>
40839
<H3><A name="Ruby_nn55"></A>30.9.2 Creating Multi-Module Packages</H3>
38383
40840
<P> The chapter on <A href="Modules.html">Working with Modules</A>
38384
40841
discusses the basics of creating multi-module extensions with SWIG, and
38385
40842
in particular the considerations for sharing runtime type information
41836
44340
<!-- INDEX -->
41837
44341
<P> R is a GPL'ed open source statistical and plotting environment.
41838
44342
Information about R can be found at <A href="http://www.r-project.org/">
41839
www.r-project.org</A>. The R binding are under active development and
41840
are extremely experimental. Not all features have been implemented and
41841
the API is not stable.</P>
44343
www.r-project.org</A>. The R bindings are under active development. They
44344
have been used to compile and run an R interface to QuantLib running on
44345
Mandriva Linux with gcc. The R bindings also work on Microsoft Windows
44346
using Visual C++.</P>
41842
44347
<H2><A name="R_nn2"></A>32.1 Bugs</H2>
41843
44348
<P> Currently the following features are not implemented or broken:</P>
41845
44350
<LI>Garbage collection of created objects</LI>
41846
44351
<LI>C Array wrappings</LI>
41847
<LI>tested on UNIX only, how well or badly it works on windows is not
41850
44353
<H2><A name="R_nn3"></A>32.2 Using R and SWIG</H2>
41851
44354
<P> To use R and SWIG in C mode, execute the following commands where
41852
example_func.c is the name of the file with the functions in them</P>
44355
example.c is the name of the file with the functions in them</P>
41853
44356
<DIV class="shell">
41855
swig -r -o example,c example.i
41856
PKG_LIBS="example_func.c" R CMD SHLIB example.c
44359
PKG_LIBS="example.c" R CMD SHLIB example_wrap.c
41859
44362
<P> The corresponding comments for C++ mode are</P>
41860
44363
<DIV class="shell">
41862
swig -c++ -r -o example.cpp example.i
41863
PKG_LIBS="example_func.cxx" R CMD SHLIB example.cpp
44365
swig -c++ -r -o example_wrap.cpp example.i
44366
PKG_LIBS="example.cxx" R CMD SHLIB example_wrap.cpp
41866
44369
<P> Note that R is sensitive to the name of the file and to the file
41867
44370
extension in C and C++ mode. The name of the wrapper file must be the
41868
name of the library. Also in C++ mode, the file extension must be cpp
41869
rather than cxx for the R compile command to recognize it.</P>
41870
<P> The commands produce two files. A dynamic shared object file called
41871
example.so and an R wrapper file called example_wrap.S. To load these
41872
files, start up R and type in the following commands</P>
44371
name of the library. Also in C++ mode, the file extension must be .cpp
44372
rather than .cxx for the R compile command to recognize it.</P>
44373
<P> The commands produces two files. A dynamic shared object file called
44374
example.so, or example.dll, and an R wrapper file called example.R. To
44375
load these files, start up R and type in the following commands</P>
41873
44376
<DIV class="shell">
41875
dyn.load('example.so')
41876
source('example_wrap.S')
44378
dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
44379
source("example.R")
44382
</DIV> The cacheMetaData(1) will cause R to refresh its object tables.
44383
Without it, inheritance of wrapped objects may fail.
41879
44384
<P> These two files can be loaded in any order</P>
41880
<H2><A name="R_nn4"></A>32.3 General policy</H2>
44385
<H2><A name="R_nn4"></A>32.3 Precompiling large R files</H2>
44386
In cases where the R file is large, one make save a lot of loading time
44387
by precompiling the R wrapper. This can be done by creating the file
44388
makeRData.R which contains the following
44390
source('BigFile.R')
44391
save(list=ls(all=TRUE),file="BigFile.RData", compress=TRUE)
44392
q(save="no")
44394
This will generate a compiled R file called BigFile.RData that will
44395
save a large amount of loading time.
44396
<H2><A name="R_nn5"></A>32.4 General policy</H2>
41881
44397
<P> The general policy of the module is to treat the C/C++ as a basic
41882
44398
wrapping over the underlying functions and rely on the R type system to
41883
44399
provide R syntax.</P>
41884
<H2><A name="R_nn5"></A>32.4 Language conventions</H2>
44400
<H2><A name="R_language_conventions"></A>32.5 Language conventions</H2>
41885
44401
<P> getitem and setitem use C++ conventions (i.e. zero based indices). [
41887
44403
and [ are overloaded to allow for R syntax (one based indices and
41891
<H2><A name="R_nn6"></A>32.5 C++ classes</H2>
44407
<H2><A name="R_nn6"></A>32.6 C++ classes</H2>
41892
44408
<P> C++ objects are implemented as external pointer objects with the
41893
44409
class being the mangled name of the class. The C++ classes are
41894
44410
encapsulated as an SEXP with an external pointer type. The class is the
41895
44411
mangled name of the class. The nice thing about R is that is allows you
41896
44412
to keep track of the pointer object which removes the necessity for a
41897
44413
lot of the proxy class baggage you see in other languages.</P>
41898
<H2><A name="R_nn7"></A>32.6 Enumerations</H2>
44414
<H2><A name="R_nn7"></A>32.7 Enumerations</H2>
41899
44415
<P> enumerations are characters which are then converted back and forth
41900
44416
to ints before calling the C routines. All of the enumeration code is
41901
44417
done in R.</P>