Fix some typos in docs and examples and make the code look nicer.

This commit is contained in:
sunoru 2016-12-31 23:06:56 +08:00
commit 8985c34809
45 changed files with 717 additions and 717 deletions

View file

@ -526,8 +526,8 @@ interested in generating an interface to C++.
<pre> <pre>
%module ffargs %module ffargs
%ffargs(strings_convert="nil",call_direct="t") foo; %ffargs(strings_convert="nil", call_direct="t") foo;
%ffargs(strings_convert="nil",release_heap=":never",optimize_for_space="t") bar; %ffargs(strings_convert="nil", release_heap=":never", optimize_for_space="t") bar;
int foo(float f1, float f2); int foo(float f1, float f2);
int foo(float f1, char c2); int foo(float f1, char c2);
@ -1357,7 +1357,7 @@ EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
arg1 = larg1; arg1 = larg1;
arg2 = larg2; arg2 = larg2;
try { try {
result = (float)xxx(arg1,arg2); result = (float)xxx(arg1, arg2);
lresult = result; lresult = result;
return lresult; return lresult;
@ -1393,7 +1393,7 @@ EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
arg1 = larg1; arg1 = larg1;
arg2 = larg2; arg2 = larg2;
try { try {
result = (float)xxx(arg1,arg2); result = (float)xxx(arg1, arg2);
lresult = result; lresult = result;
return lresult; return lresult;
@ -1526,8 +1526,8 @@ overload&gt;
%rename(__predecr__) *::operator--(); %rename(__predecr__) *::operator--();
%rename(__postdecr__) *::operator--(int); %rename(__postdecr__) *::operator--(int);
%rename(__comma__) *::operator,(); %rename(__comma__) *::operator, ();
%rename(__comma__) *::operator,() const; %rename(__comma__) *::operator, () const;
%rename(__member_ref__) *::operator-&gt;; %rename(__member_ref__) *::operator-&gt;;
%rename(__member_func_ref__) *::operator-&gt;*; %rename(__member_func_ref__) *::operator-&gt;*;

View file

@ -354,7 +354,7 @@ Modify the <tt>nativeCall</tt> method in <tt>src/org/swig/simple/SwigSimple.java
int x = 42; int x = 42;
int y = 105; int y = 105;
int g = example.gcd(x,y); int g = example.gcd(x, y);
outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n"); outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n");
// Manipulate the Foo global variable // Manipulate the Foo global variable
@ -661,7 +661,7 @@ public class SwigClass extends Activity
// ----- Call some methods ----- // ----- Call some methods -----
outputText.append( "\nHere are some properties of the shapes:\n" ); outputText.append( "\nHere are some properties of the shapes:\n" );
Shape[] shapes = {c,s}; Shape[] shapes = {c, s};
for (int i=0; i&lt;shapes.length; i++) for (int i=0; i&lt;shapes.length; i++)
{ {
outputText.append( " " + shapes[i].toString() + "\n" ); outputText.append( " " + shapes[i].toString() + "\n" );

View file

@ -100,7 +100,7 @@ like this (shown for Python):
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; a = add(3,4) &gt;&gt;&gt; a = add(3, 4)
&gt;&gt;&gt; print a &gt;&gt;&gt; print a
7 7
&gt;&gt;&gt; &gt;&gt;&gt;
@ -148,7 +148,7 @@ For example, consider this code:
%include "typemaps.i" %include "typemaps.i"
%apply int *OUTPUT { int *width, int *height }; %apply int *OUTPUT { int *width, int *height };
// Returns a pair (width,height) // Returns a pair (width, height)
void getwinsize(int winid, int *width, int *height); void getwinsize(int winid, int *width, int *height);
</pre> </pre>
</div> </div>
@ -158,7 +158,7 @@ In this case, the function returns multiple values, allowing it to be used like
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; w,h = genwinsize(wid) &gt;&gt;&gt; w, h = genwinsize(wid)
&gt;&gt;&gt; print w &gt;&gt;&gt; print w
400 400
&gt;&gt;&gt; print h &gt;&gt;&gt; print h
@ -245,7 +245,7 @@ When the function is used in the scripting language interpreter, it will work li
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
result = add(3,4) result = add(3, 4)
</pre></div> </pre></div>
<H3><a name="Arguments_nn5">10.1.3 Output parameters</a></H3> <H3><a name="Arguments_nn5">10.1.3 Output parameters</a></H3>

View file

@ -203,7 +203,7 @@ public:
<p>And then call this constructor from your target language, for example, in Python, the following will call the constructor taking the <tt>std::vector</tt>:</p> <p>And then call this constructor from your target language, for example, in Python, the following will call the constructor taking the <tt>std::vector</tt>:</p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; c = Container( [1,2,3,4] ) &gt;&gt;&gt; c = Container( [1, 2, 3, 4] )
</pre></div> </pre></div>
<p> <p>
@ -392,7 +392,7 @@ auto SomeStruct::FuncName(int x, int y) -&gt; int {
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; a = SomeStruct() &gt;&gt;&gt; a = SomeStruct()
&gt;&gt;&gt; a.FuncName(10,5) &gt;&gt;&gt; a.FuncName(10, 5)
15 15
</pre></div> </pre></div>
@ -1057,7 +1057,7 @@ It does not involve <tt>std::function</tt>.
<div class="targetlang"><pre> <div class="targetlang"><pre>
t = Test() t = Test()
b = t(1,2) # invoke C++ function object b = t(1, 2) # invoke C++ function object
</pre></div> </pre></div>
<H3><a name="CPlusPlus11_type_traits_for_metaprogramming">7.3.9 Type traits for metaprogramming</a></H3> <H3><a name="CPlusPlus11_type_traits_for_metaprogramming">7.3.9 Type traits for metaprogramming</a></H3>

View file

@ -602,7 +602,7 @@ For the <tt>%array_functions</tt> example, the equivalent usage would be:
<pre> <pre>
SWIGTYPE_p_double a = example.new_doubleArray(10); // Create an array SWIGTYPE_p_double a = example.new_doubleArray(10); // Create an array
for (int i=0; i&lt;10; i++) for (int i=0; i&lt;10; i++)
example.doubleArray_setitem(a,i,2*i); // Set a value example.doubleArray_setitem(a, i, 2*i); // Set a value
example.print_array(a); // Pass to C example.print_array(a); // Pass to C
example.delete_doubleArray(a); // Destroy array example.delete_doubleArray(a); // Destroy array
</pre> </pre>
@ -1684,7 +1684,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &amp;b, bool flag) {
unsigned int jflag ; unsigned int jflag ;
if (!swig_callbackBaseBoolMethod) { if (!swig_callbackBaseBoolMethod) {
Base::BaseBoolMethod(b,flag); Base::BaseBoolMethod(b, flag);
return; return;
} else { } else {
jb = (Base *) &amp;b; jb = (Base *) &amp;b;
@ -2160,7 +2160,7 @@ The typemaps to achieve this are shown below.
%typemap(cstype) CDate &amp; "out System.DateTime" %typemap(cstype) CDate &amp; "out System.DateTime"
%typemap(csin, %typemap(csin,
pre=" CDate temp$csinput = new CDate();", pre=" CDate temp$csinput = new CDate();",
post=" $csinput = new System.DateTime(temp$csinput.getYear()," post=" $csinput = new System.DateTime(temp$csinput.getYear(), "
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
cshin="out $csinput" cshin="out $csinput"
) CDate &amp; ) CDate &amp;
@ -2266,7 +2266,7 @@ will be possible with the following <tt>CDate *</tt> typemaps
%typemap(csin, %typemap(csin,
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);", pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
post=" $csinput = new System.DateTime(temp$csinput.getYear()," post=" $csinput = new System.DateTime(temp$csinput.getYear(), "
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
cshin="ref $csinput" cshin="ref $csinput"
) CDate * ) CDate *
@ -2305,7 +2305,7 @@ The <tt>subtractYears</tt> method is nearly identical to the above <tt>addYears<
<pre> <pre>
%typemap(csin, %typemap(csin,
pre=" using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {", pre=" using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
post=" $csinput = new System.DateTime(temp$csinput.getYear()," post=" $csinput = new System.DateTime(temp$csinput.getYear(), "
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
terminator=" } // terminate temp$csinput using block", terminator=" } // terminate temp$csinput using block",
cshin="ref $csinput" cshin="ref $csinput"
@ -2377,7 +2377,7 @@ The typemap type required is thus <tt>CDate *</tt>. Given that the previous sect
%typemap(csin, %typemap(csin,
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);", pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
post=" $csinput = new System.DateTime(temp$csinput.getYear()," post=" $csinput = new System.DateTime(temp$csinput.getYear(), "
" temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
cshin="ref $csinput" cshin="ref $csinput"
) CDate * ) CDate *

View file

@ -297,7 +297,7 @@
The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:
"Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a
metaobject protocol. The implementation is even simpler than metaobject protocol. The implementation is even simpler than
the simple CLOS found in `The Art of the Metaobject Protocol,' the simple CLOS found in `The Art of the Metaobject Protocol, '
weighing in at around 850 lines of code, including (some) weighing in at around 850 lines of code, including (some)
comments and documentation." comments and documentation."
</p> </p>
@ -420,7 +420,7 @@ See the
Loading-extension-libraries in the eval unit inside the CHICKEN manual for more information.</p> Loading-extension-libraries in the eval unit inside the CHICKEN manual for more information.</p>
<p>Another alternative is to run SWIG normally and create a scheme file that contains <code>(declare (uses <i>modname</i>))</code> <p>Another alternative is to run SWIG normally and create a scheme file that contains <code>(declare (uses <i>modname</i>))</code>
and then compile that file into the shared library as well. For example, inside the <tt>mod_load.scm</tt> file,</p> and then compile that file into the shared library as well. For example, inside the <tt>mod_load.scm</tt> file, </p>
<div class="targetlang"> <div class="targetlang">
<pre> <pre>

View file

@ -133,7 +133,7 @@ Thus, any contract that you specified for a base class will also be attached to
<pre> <pre>
class Spam : public Foo { class Spam : public Foo {
public: public:
int bar(int,int); // Gets contract defined for Foo::bar(int,int) int bar(int, int); // Gets contract defined for Foo::bar(int, int)
}; };
</pre> </pre>
</div> </div>
@ -156,12 +156,12 @@ require:
class Foo { class Foo {
public: public:
int bar(int,int); // Gets Foo::bar contract. int bar(int, int); // Gets Foo::bar contract.
}; };
class Spam : public Foo { class Spam : public Foo {
public: public:
int bar(int,int); // Gets Foo::bar and Spam::bar contract int bar(int, int); // Gets Foo::bar and Spam::bar contract
}; };
</pre> </pre>
</div> </div>

View file

@ -75,7 +75,7 @@ How the exception is handled depends on the target language, for example, Python
$action $action
} }
catch (RangeError) { catch (RangeError) {
PyErr_SetString(PyExc_IndexError,"index out-of-bounds"); PyErr_SetString(PyExc_IndexError, "index out-of-bounds");
SWIG_fail; SWIG_fail;
} }
} }
@ -116,7 +116,7 @@ static char error_message[256];
static int error_status = 0; static int error_status = 0;
void throw_exception(char *msg) { void throw_exception(char *msg) {
strncpy(error_message,msg,256); strncpy(error_message, msg, 256);
error_status = 1; error_status = 1;
} }
@ -193,7 +193,7 @@ extern int exception_status;
#define try if ((exception_status = setjmp(exception_buffer)) == 0) #define try if ((exception_status = setjmp(exception_buffer)) == 0)
#define catch(val) else if (exception_status == val) #define catch(val) else if (exception_status == val)
#define throw(val) longjmp(exception_buffer,val) #define throw(val) longjmp(exception_buffer, val)
#define finally else #define finally else
/* Exception codes */ /* Exception codes */
@ -569,7 +569,7 @@ common scripting language exceptions in a portable manner. For example :</p>
} catch(OutOfMemory) { } catch(OutOfMemory) {
SWIG_exception(SWIG_MemoryError, "Out of memory"); SWIG_exception(SWIG_MemoryError, "Out of memory");
} catch(...) { } catch(...) {
SWIG_exception(SWIG_RuntimeError,"Unknown exception"); SWIG_exception(SWIG_RuntimeError, "Unknown exception");
} }
} }
@ -645,7 +645,7 @@ you can attach it to class members and parameterized declarations as before. Fo
<div class="code"> <div class="code">
<pre> <pre>
%newobject ::blah(); // Only applies to global blah %newobject ::blah(); // Only applies to global blah
%newobject Object::blah(int,double); // Only blah(int,double) in Object %newobject Object::blah(int, double); // Only blah(int, double) in Object
%newobject *::copy; // Copy method in all classes %newobject *::copy; // Copy method in all classes
... ...
</pre> </pre>
@ -779,7 +779,7 @@ using the <tt>%feature</tt> directive. For example:
} }
} }
%feature("new","1") *::copy; %feature("new", "1") *::copy;
</pre> </pre>
</div> </div>
@ -791,7 +791,7 @@ involving <tt>%feature</tt>:
<div class="code"> <div class="code">
<pre> <pre>
#define %exception %feature("except") #define %exception %feature("except")
#define %newobject %feature("new","1") #define %newobject %feature("new", "1")
</pre> </pre>
</div> </div>
@ -831,7 +831,7 @@ The following are all equivalent:
%feature("except") Object::method { $action }; %feature("except") Object::method { $action };
%feature("except") Object::method %{ $action %}; %feature("except") Object::method %{ $action %};
%feature("except") Object::method " $action "; %feature("except") Object::method " $action ";
%feature("except","$action") Object::method; %feature("except", "$action") Object::method;
</pre> </pre>
</div> </div>
@ -850,7 +850,7 @@ The following is the generic syntax for features:
<div class="code"> <div class="code">
<pre> <pre>
%feature("name","value", attribute1="AttributeValue1") symbol; %feature("name", "value", attribute1="AttributeValue1") symbol;
%feature("name", attribute1="AttributeValue1") symbol {value}; %feature("name", attribute1="AttributeValue1") symbol {value};
%feature("name", attribute1="AttributeValue1") symbol %{value%}; %feature("name", attribute1="AttributeValue1") symbol %{value%};
%feature("name", attribute1="AttributeValue1") symbol "value"; %feature("name", attribute1="AttributeValue1") symbol "value";
@ -914,13 +914,13 @@ int red; // mutable
%feature("immutable"); // global enable %feature("immutable"); // global enable
int orange; // immutable int orange; // immutable
%feature("immutable","0"); // global disable %feature("immutable", "0"); // global disable
int yellow; // mutable int yellow; // mutable
%feature("immutable","1"); // another form of global enable %feature("immutable", "1"); // another form of global enable
int green; // immutable int green; // immutable
%feature("immutable",""); // clears the global feature %feature("immutable", ""); // clears the global feature
int blue; // mutable int blue; // mutable
</pre> </pre>
</div> </div>
@ -932,8 +932,8 @@ The above intersperses SWIG directives with C code. Of course you can target fea
<div class="code"> <div class="code">
<pre> <pre>
%feature("immutable","1") orange; %feature("immutable", "1") orange;
%feature("immutable","1") green; %feature("immutable", "1") green;
int red; // mutable int red; // mutable
int orange; // immutable int orange; // immutable
int yellow; // mutable int yellow; // mutable
@ -949,10 +949,10 @@ The logic above can of course be inverted and rewritten as:
<div class="code"> <div class="code">
<pre> <pre>
%feature("immutable","1"); %feature("immutable", "1");
%feature("immutable","0") red; %feature("immutable", "0") red;
%feature("immutable","0") yellow; %feature("immutable", "0") yellow;
%feature("immutable","0") blue; %feature("immutable", "0") blue;
int red; // mutable int red; // mutable
int orange; // immutable int orange; // immutable
int yellow; // mutable int yellow; // mutable
@ -983,7 +983,7 @@ The concept of clearing features is discussed next.
<p> <p>
A feature stays in effect until it is explicitly cleared. A feature is cleared by A feature stays in effect until it is explicitly cleared. A feature is cleared by
supplying a <tt>%feature</tt> directive with no value. For example <tt>%feature("name","")</tt>. supplying a <tt>%feature</tt> directive with no value. For example <tt>%feature("name", "")</tt>.
A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules. A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules.
So if a feature is cleared, it might mean that another name matching rule will apply. So if a feature is cleared, it might mean that another name matching rule will apply.
To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt>): To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt>):
@ -1013,7 +1013,7 @@ To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt
... initial set of class declarations with clone methods ... ... initial set of class declarations with clone methods ...
// clear the previously defined feature // clear the previously defined feature
%feature("except","") *::clone(); %feature("except", "") *::clone();
... final set of class declarations with clone methods ... ... final set of class declarations with clone methods ...
</pre> </pre>
@ -1027,8 +1027,8 @@ However, these clone methods will still have an exception handler (without loggi
<p> <p>
Note that clearing a feature is not always the same as disabling it. Note that clearing a feature is not always the same as disabling it.
Clearing the feature above with <tt>%feature("except","") *::clone()</tt> is not the same as specifying Clearing the feature above with <tt>%feature("except", "") *::clone()</tt> is not the same as specifying
<tt>%feature("except","0") *::clone()</tt>. The former will disable the feature for clone methods - <tt>%feature("except", "0") *::clone()</tt>. The former will disable the feature for clone methods -
the feature is still a better match than the global feature. the feature is still a better match than the global feature.
If on the other hand, no global exception handler had been defined at all, If on the other hand, no global exception handler had been defined at all,
then clearing the feature would be the same as disabling it as no other feature would have matched. then clearing the feature would be the same as disabling it as no other feature would have matched.
@ -1042,7 +1042,7 @@ For example the following attempt to clear the initial feature will not work:
<div class="code"> <div class="code">
<pre> <pre>
%feature("except") clone() { logger.info("$action"); $action } %feature("except") clone() { logger.info("$action"); $action }
%feature("except","") *::clone(); %feature("except", "") *::clone();
</pre> </pre>
</div> </div>
@ -1053,7 +1053,7 @@ but this will:
<div class="code"> <div class="code">
<pre> <pre>
%feature("except") clone() { logger.info("$action"); $action } %feature("except") clone() { logger.info("$action"); $action }
%feature("except","") clone(); %feature("except", "") clone();
</pre> </pre>
</div> </div>
@ -1066,8 +1066,8 @@ The three macros below show this for the "except" feature:
<div class="code"> <div class="code">
<pre> <pre>
#define %exception %feature("except") #define %exception %feature("except")
#define %noexception %feature("except","0") #define %noexception %feature("except", "0")
#define %clearexception %feature("except","") #define %clearexception %feature("except", "")
</pre> </pre>
</div> </div>
@ -1158,15 +1158,15 @@ in the Python module. You might use <tt>%feature</tt> to rewrite proxy/shadow cl
<div class="code"> <div class="code">
<pre> <pre>
%module example %module example
%rename(bar_id) bar(int,double); %rename(bar_id) bar(int, double);
// Rewrite bar() to allow some nice overloading // Rewrite bar() to allow some nice overloading
%feature("shadow") Foo::bar(int) %{ %feature("shadow") Foo::bar(int) %{
def bar(*args): def bar(*args):
if len(args) == 3: if len(args) == 3:
return apply(examplec.Foo_bar_id,args) return apply(examplec.Foo_bar_id, args)
return apply(examplec.Foo_bar,args) return apply(examplec.Foo_bar, args)
%} %}
class Foo { class Foo {

View file

@ -422,7 +422,7 @@ struct A {
<p>As with any other language, the SWIG test-suite can be built for D using the <tt>*-d-test-suite</tt> targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional <tt>D_VERSION</tt> variable, e.g. <tt>make check-d-test-suite D_VERSION=2</tt>.</p> <p>As with any other language, the SWIG test-suite can be built for D using the <tt>*-d-test-suite</tt> targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional <tt>D_VERSION</tt> variable, e.g. <tt>make check-d-test-suite D_VERSION=2</tt>.</p>
<p>Note: If you want to use GDC on Linux or another platform which requires you to link <tt>libdl</tt> for dynamically loading the shared library, you might have to add <tt>-ldl</tt> manually to the <tt>d_compile</tt> target in <tt>Examples/Makefile</tt>, because GDC does not currently honor the <tt>pragma(lib,...)</tt> statement.</p> <p>Note: If you want to use GDC on Linux or another platform which requires you to link <tt>libdl</tt> for dynamically loading the shared library, you might have to add <tt>-ldl</tt> manually to the <tt>d_compile</tt> target in <tt>Examples/Makefile</tt>, because GDC does not currently honor the <tt>pragma(lib, ...)</tt> statement.</p>
<H2><a name="D_typemap_examples">22.9 D Typemap examples</a></H2> <H2><a name="D_typemap_examples">22.9 D Typemap examples</a></H2>

View file

@ -243,7 +243,7 @@ of <tt>swig.swg</tt> looks like this:
/* Access control directives */ /* Access control directives */
#define %immutable %feature("immutable","1") #define %immutable %feature("immutable", "1")
#define %mutable %feature("immutable") #define %mutable %feature("immutable")
/* Directives for callback functions */ /* Directives for callback functions */
@ -306,7 +306,7 @@ datatype such as <tt>int</tt> or <tt>void</tt>. <tt><em>type</em></tt> may be
qualified with a qualifier such as <tt>const</tt> or <tt>volatile</tt>. <tt><em>declarator</em></tt> qualified with a qualifier such as <tt>const</tt> or <tt>volatile</tt>. <tt><em>declarator</em></tt>
is a name with additional type-construction modifiers attached to it (pointers, arrays, references, is a name with additional type-construction modifiers attached to it (pointers, arrays, references,
functions, etc.). Examples of declarators include <tt>*x</tt>, <tt>**x</tt>, <tt>x[20]</tt>, and functions, etc.). Examples of declarators include <tt>*x</tt>, <tt>**x</tt>, <tt>x[20]</tt>, and
<tt>(*x)(int,double)</tt>. The <tt><em>initializer</em></tt> may be a value assigned using <tt>=</tt> or <tt>(*x)(int, double)</tt>. The <tt><em>initializer</em></tt> may be a value assigned using <tt>=</tt> or
body of code enclosed in braces <tt>{ ... }</tt>. body of code enclosed in braces <tt>{ ... }</tt>.
</p> </p>
@ -372,7 +372,7 @@ For example, in an old C program, you might see things like this:
<div class="code"> <div class="code">
<pre> <pre>
foo(a,b) { foo(a, b) {
... ...
} }
</pre> </pre>
@ -516,8 +516,8 @@ $ swig -c++ -python -debug-module 4 example.i
+++ cdecl ---------------------------------------- +++ cdecl ----------------------------------------
| sym:name - "move" | sym:name - "move"
| name - "move" | name - "move"
| decl - "f(double,double)." | decl - "f(double, double)."
| parms - double ,double | parms - double, double
| type - "void" | type - "void"
| sym:symtab - 0x40194140 | sym:symtab - 0x40194140
| |
@ -1381,14 +1381,14 @@ List *l = (some list);
Iterator i; Iterator i;
for (i = First(l); i.item; i = Next(i)) { for (i = First(l); i.item; i = Next(i)) {
Printf(stdout,"%s\n", i.item); Printf(stdout, "%s\n", i.item);
} }
Hash *h = (some hash); Hash *h = (some hash);
Iterator j; Iterator j;
for (j = First(j); j.item; j= Next(j)) { for (j = First(j); j.item; j= Next(j)) {
Printf(stdout,"%s : %s\n", j.key, j.item); Printf(stdout, "%s : %s\n", j.key, j.item);
} }
</pre> </pre>
</div> </div>
@ -1414,7 +1414,7 @@ operators have the same meaning.
</div> </div>
<p> <p>
<b><tt>int Printv(String_or_FILE *f, String_or_char *arg1,..., NULL)</tt></b> <b><tt>int Printv(String_or_FILE *f, String_or_char *arg1, ..., NULL)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -1469,7 +1469,7 @@ Same as the C <tt>ungetc()</tt> function.
<div class="indent"> <div class="indent">
Same as the C <tt>seek()</tt> function. <tt>offset</tt> is the number Same as the C <tt>seek()</tt> function. <tt>offset</tt> is the number
of bytes. <tt>whence</tt> is one of <tt>SEEK_SET</tt>,<tt>SEEK_CUR</tt>, of bytes. <tt>whence</tt> is one of <tt>SEEK_SET</tt>, <tt>SEEK_CUR</tt>,
or <tt>SEEK_END</tt>.. or <tt>SEEK_END</tt>..
</div> </div>
@ -1515,9 +1515,9 @@ common to see small code fragments of code generated using code like this:
<pre> <pre>
/* Print into a string */ /* Print into a string */
String *s = NewString(""); String *s = NewString("");
Printf(s,"Hello\n"); Printf(s, "Hello\n");
for (i = 0; i &lt; 10; i++) { for (i = 0; i &lt; 10; i++) {
Printf(s,"%d\n", i); Printf(s, "%d\n", i);
} }
... ...
/* Print string into a file */ /* Print string into a file */
@ -1674,9 +1674,9 @@ Since parse tree nodes are just hash tables, attributes are accessed using the <
<div class="code"> <div class="code">
<pre> <pre>
int functionHandler(Node *n) { int functionHandler(Node *n) {
String *name = Getattr(n,"name"); String *name = Getattr(n, "name");
String *symname = Getattr(n,"sym:name"); String *symname = Getattr(n, "sym:name");
SwigType *type = Getattr(n,"type"); SwigType *type = Getattr(n, "type");
... ...
} }
</pre> </pre>
@ -1691,7 +1691,7 @@ For example:
<div class="code"> <div class="code">
<pre> <pre>
... ...
Setattr(n,"python:docstring", doc); /* Store docstring */ Setattr(n, "python:docstring", doc); /* Store docstring */
... ...
</pre> </pre>
</div> </div>
@ -1702,7 +1702,7 @@ A quick way to check the value of an attribute is to use the <tt>checkAttribute(
<div class="code"> <div class="code">
<pre> <pre>
if (checkAttribute(n,"storage","virtual")) { if (checkAttribute(n, "storage", "virtual")) {
/* n is virtual */ /* n is virtual */
... ...
} }
@ -1723,7 +1723,7 @@ the following functions are used:
<div class="indent"> <div class="indent">
Saves a copy of attributes <tt>name1</tt>, <tt>name2</tt>, etc. from node <tt>n</tt>. Saves a copy of attributes <tt>name1</tt>, <tt>name2</tt>, etc. from node <tt>n</tt>.
Copies of the attributes are actually resaved in the node in a different namespace which is Copies of the attributes are actually resaved in the node in a different namespace which is
set by the <tt>ns</tt> argument. For example, if you call <tt>Swig_save("foo",n,"type",NIL)</tt>, set by the <tt>ns</tt> argument. For example, if you call <tt>Swig_save("foo", n, "type", NIL)</tt>,
then the "type" attribute will be copied and saved as "foo:type". The namespace name itself is stored in then the "type" attribute will be copied and saved as "foo:type". The namespace name itself is stored in
the "view" attribute of the node. If necessary, this can be examined to find out where previous the "view" attribute of the node. If necessary, this can be examined to find out where previous
values of attributes might have been saved. values of attributes might have been saved.
@ -1750,11 +1750,11 @@ Calls can be nested if necessary. Here is an example that shows how the functio
<div class="code"> <div class="code">
<pre> <pre>
int variableHandler(Node *n) { int variableHandler(Node *n) {
Swig_save("variableHandler",n,"type","sym:name",NIL); Swig_save("variableHandler", n, "type", "sym:name", NIL);
String *symname = Getattr(n,"sym:name"); String *symname = Getattr(n, "sym:name");
SwigType *type = Getattr(n,"type"); SwigType *type = Getattr(n, "type");
... ...
Append(symname,"_global"); // Change symbol name Append(symname, "_global"); // Change symbol name
SwigType_add_pointer(type); // Add pointer SwigType_add_pointer(type); // Add pointer
... ...
generate wrappers generate wrappers
@ -1808,7 +1808,7 @@ C datatype SWIG encoding (strings)
int "int" int "int"
int * "p.int" int * "p.int"
const int * "p.q(const).int" const int * "p.q(const).int"
int (*x)(int,double) "p.f(int,double).int" int (*x)(int, double) "p.f(int, double).int"
int [20][30] "a(20).a(30).int" int [20][30] "a(20).a(30).int"
int (F::*)(int) "m(F).f(int).int" int (F::*)(int) "m(F).f(int).int"
vector&lt;int&gt; * "p.vector&lt;(int)&gt;" vector&lt;int&gt; * "p.vector&lt;(int)&gt;"
@ -1817,8 +1817,8 @@ vector&lt;int&gt; * "p.vector&lt;(int)&gt;"
<p> <p>
Reading the SWIG encoding is often easier than figuring out the C code---just Reading the SWIG encoding is often easier than figuring out the C code---just
read it from left to right. For a type of "p.f(int,double).int" is read it from left to right. For a type of "p.f(int, double).int" is
a "pointer to a function(int,double) that returns int". a "pointer to a function(int, double) that returns int".
</p> </p>
<p> <p>
@ -1854,7 +1854,7 @@ an extremely perverted example:
<div class="diagram"> <div class="diagram">
<pre> <pre>
`p.a(10).p.f(int,p.f(int).int)` foo(int, int (*x)(int)); `p.a(10).p.f(int, p.f(int).int)` foo(int, int (*x)(int));
</pre> </pre>
</div> </div>
@ -1864,7 +1864,7 @@ This corresponds to the immediately obvious C declaration:
<div class="diagram"> <div class="diagram">
<pre> <pre>
(*(*foo(int,int (*)(int)))[10])(int,int (*)(int)); (*(*foo(int, int (*)(int)))[10])(int, int (*)(int));
</pre> </pre>
</div> </div>
@ -1947,7 +1947,7 @@ Returns number of array dimensions of <tt>ty</tt>.
</div> </div>
<p> <p>
<b><tt>String* SwigType_array_getdim(SwigType *ty,int n)</tt></b> <b><tt>String* SwigType_array_getdim(SwigType *ty, int n)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -2375,9 +2375,9 @@ code like this:
Parm *parms; Parm *parms;
Parm *p; Parm *p;
for (p = parms; p; p = nextSibling(p)) { for (p = parms; p; p = nextSibling(p)) {
SwigType *type = Getattr(p,"type"); SwigType *type = Getattr(p, "type");
String *name = Getattr(p,"name"); String *name = Getattr(p, "name");
String *value = Getattr(p,"value"); String *value = Getattr(p, "value");
... ...
} }
</pre> </pre>
@ -2537,7 +2537,7 @@ also return a pointer to the base class (<tt>Language</tt>) so that only the int
Save the code for your language module in a file named "<tt>python.cxx</tt>" and Save the code for your language module in a file named "<tt>python.cxx</tt>" and
place this file in the <tt>Source/Modules</tt> directory of the SWIG distribution. place this file in the <tt>Source/Modules</tt> directory of the SWIG distribution.
To ensure that your module is compiled into SWIG along with the other language modules, To ensure that your module is compiled into SWIG along with the other language modules,
modify the file <tt>Source/Modules/Makefile.am</tt> to include the additional source modify the file <tt>Source/Makefile.am</tt> to include the additional source
files. In addition, modify the file <tt>Source/Modules/swigmain.cxx</tt> files. In addition, modify the file <tt>Source/Modules/swigmain.cxx</tt>
with an additional command line option that activates the module. Read the source---it's straightforward. with an additional command line option that activates the module. Read the source---it's straightforward.
</p> </p>
@ -2593,7 +2593,7 @@ command line options, simply use code similar to this:
void Language::main(int argc, char *argv[]) { void Language::main(int argc, char *argv[]) {
for (int i = 1; i &lt; argc; i++) { for (int i = 1; i &lt; argc; i++) {
if (argv[i]) { if (argv[i]) {
if(strcmp(argv[i],"-interface") == 0) { if (strcmp(argv[i], "-interface") == 0) {
if (argv[i+1]) { if (argv[i+1]) {
interface = NewString(argv[i+1]); interface = NewString(argv[i+1]);
Swig_mark_arg(i); Swig_mark_arg(i);
@ -2602,7 +2602,7 @@ void Language::main(int argc, char *argv[]) {
} else { } else {
Swig_arg_error(); Swig_arg_error();
} }
} else if (strcmp(argv[i],"-globals") == 0) { } else if (strcmp(argv[i], "-globals") == 0) {
if (argv[i+1]) { if (argv[i+1]) {
global_name = NewString(argv[i+1]); global_name = NewString(argv[i+1]);
Swig_mark_arg(i); Swig_mark_arg(i);
@ -2611,14 +2611,14 @@ void Language::main(int argc, char *argv[]) {
} else { } else {
Swig_arg_error(); Swig_arg_error();
} }
} else if ( (strcmp(argv[i],"-proxy") == 0)) { } else if ((strcmp(argv[i], "-proxy") == 0)) {
proxy_flag = 1; proxy_flag = 1;
Swig_mark_arg(i); Swig_mark_arg(i);
} else if (strcmp(argv[i],"-keyword") == 0) { } else if (strcmp(argv[i], "-keyword") == 0) {
use_kw = 1; use_kw = 1;
Swig_mark_arg(i); Swig_mark_arg(i);
} else if (strcmp(argv[i],"-help") == 0) { } else if (strcmp(argv[i], "-help") == 0) {
fputs(usage,stderr); fputs(usage, stderr);
} }
... ...
} }
@ -2722,10 +2722,10 @@ An outline of <tt>top()</tt> might be as follows:
int Python::top(Node *n) { int Python::top(Node *n) {
/* Get the module name */ /* Get the module name */
String *module = Getattr(n,"name"); String *module = Getattr(n, "name");
/* Get the output file name */ /* Get the output file name */
String *outfile = Getattr(n,"outfile"); String *outfile = Getattr(n, "outfile");
/* Initialize I/O (see next section) */ /* Initialize I/O (see next section) */
... ...
@ -2858,15 +2858,15 @@ A simple modification to write some basic details to the wrapper looks like this
<pre> <pre>
int Python::functionWrapper(Node *n) { int Python::functionWrapper(Node *n) {
/* Get some useful attributes of this function */ /* Get some useful attributes of this function */
String *name = Getattr(n,"sym:name"); String *name = Getattr(n, "sym:name");
SwigType *type = Getattr(n,"type"); SwigType *type = Getattr(n, "type");
ParmList *parms = Getattr(n,"parms"); ParmList *parms = Getattr(n, "parms");
String *parmstr= ParmList_str_defaultargs(parms); // to string String *parmstr= ParmList_str_defaultargs(parms); // to string
String *func = SwigType_str(type, NewStringf("%s(%s)", name, parmstr)); String *func = SwigType_str(type, NewStringf("%s(%s)", name, parmstr));
String *action = Getattr(n,"wrap:action"); String *action = Getattr(n, "wrap:action");
Printf(f_wrappers,"functionWrapper : %s\n", func); Printf(f_wrappers, "functionWrapper : %s\n", func);
Printf(f_wrappers," action : %s\n", action); Printf(f_wrappers, " action : %s\n", action);
return SWIG_OK; return SWIG_OK;
} }
</pre> </pre>
@ -2881,13 +2881,13 @@ This will now produce some useful information within your wrapper file.
functionWrapper : void delete_Shape(Shape *self) functionWrapper : void delete_Shape(Shape *self)
action : delete arg1; action : delete arg1;
functionWrapper : void Shape_x_set(Shape *self,double x) functionWrapper : void Shape_x_set(Shape *self, double x)
action : if (arg1) (arg1)-&gt;x = arg2; action : if (arg1) (arg1)-&gt;x = arg2;
functionWrapper : double Shape_x_get(Shape *self) functionWrapper : double Shape_x_get(Shape *self)
action : result = (double) ((arg1)-&gt;x); action : result = (double) ((arg1)-&gt;x);
functionWrapper : void Shape_y_set(Shape *self,double y) functionWrapper : void Shape_y_set(Shape *self, double y)
action : if (arg1) (arg1)-&gt;y = arg2; action : if (arg1) (arg1)-&gt;y = arg2;
... ...
</pre> </pre>
@ -2918,7 +2918,7 @@ In general most language wrappers look a little like this:
</p> </p>
<div class="code"> <div class="code">
<pre> <pre>
/* wrapper for TYPE3 some_function(TYPE1,TYPE2); */ /* wrapper for TYPE3 some_function(TYPE1, TYPE2); */
RETURN_TYPE _wrap_some_function(ARGS){ RETURN_TYPE _wrap_some_function(ARGS){
TYPE1 arg1; TYPE1 arg1;
TYPE2 arg2; TYPE2 arg2;
@ -2929,7 +2929,7 @@ RETURN_TYPE _wrap_some_function(ARGS){
if(ARG2 is not of TYPE2) goto fail; if(ARG2 is not of TYPE2) goto fail;
arg2=(convert ARG2); arg2=(convert ARG2);
result=some_function(arg1,arg2); result=some_function(arg1, arg2);
convert 'result' to whatever the language wants; convert 'result' to whatever the language wants;
@ -2973,9 +2973,9 @@ There are a lot of issues to address.
<pre> <pre>
virtual int functionWrapper(Node *n) { virtual int functionWrapper(Node *n) {
/* get useful attributes */ /* get useful attributes */
String *name = Getattr(n,"sym:name"); String *name = Getattr(n, "sym:name");
SwigType *type = Getattr(n,"type"); SwigType *type = Getattr(n, "type");
ParmList *parms = Getattr(n,"parms"); ParmList *parms = Getattr(n, "parms");
... ...
/* create the wrapper object */ /* create the wrapper object */
@ -2988,7 +2988,7 @@ virtual int functionWrapper(Node *n) {
.... ....
/* write the wrapper function definition */ /* write the wrapper function definition */
Printv(wrapper-&gt;def,"RETURN_TYPE ", wname, "(ARGS) {",NIL); Printv(wrapper-&gt;def, "RETURN_TYPE ", wname, "(ARGS) {", NIL);
/* if any additional local variable needed, add them now */ /* if any additional local variable needed, add them now */
... ...
@ -3006,7 +3006,7 @@ virtual int functionWrapper(Node *n) {
.... ....
/* Emit the function call */ /* Emit the function call */
emit_action(n,wrapper); emit_action(n, wrapper);
/* return value if necessary */ /* return value if necessary */
.... ....
@ -3030,7 +3030,7 @@ virtual int functionWrapper(Node *n) {
... ...
/* Dump the function out */ /* Dump the function out */
Wrapper_print(wrapper,f_wrappers); Wrapper_print(wrapper, f_wrappers);
/* tidy up */ /* tidy up */
Delete(wname); Delete(wname);

View file

@ -1337,7 +1337,7 @@ func Modf(x float64) (fracPart float64, intPart float64) {
<p>For classes, since swig generates an interface, you can add additional <p>For classes, since swig generates an interface, you can add additional
methods by defining another interface that includes the swig-generated methods by defining another interface that includes the swig-generated
interface. For example,</p> interface. For example, </p>
<div class="code"> <div class="code">
<pre> <pre>
%rename(Wrapped_MyClass) MyClass; %rename(Wrapped_MyClass) MyClass;
@ -1372,7 +1372,7 @@ few, then you might as well define your own struct that includes the
swig-wrapped object, instead of adding methods to the swig-generated object.</p> swig-wrapped object, instead of adding methods to the swig-generated object.</p>
<p>If you need to import other go packages, you can do this with <p>If you need to import other go packages, you can do this with
<code>%go_import</code>. For example,</p> <code>%go_import</code>. For example, </p>
<div class="code"> <div class="code">
<pre> <pre>
%go_import("fmt", _ "unusedPackage", rp "renamed/package") %go_import("fmt", _ "unusedPackage", rp "renamed/package")

View file

@ -727,7 +727,7 @@ In the previous example, the GOOPS definitions will be in a file named Test.scm.
<p>Because of the naming conflicts, you can't in general use both the <code>-primitive</code> and the GOOPS <p>Because of the naming conflicts, you can't in general use both the <code>-primitive</code> and the GOOPS
guile-modules at the same time. To do this, you need to rename the exported symbols from one or both guile-modules at the same time. To do this, you need to rename the exported symbols from one or both
guile-modules. For example,</p> guile-modules. For example, </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
(use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:))) (use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
(use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:))) (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))

View file

@ -251,7 +251,7 @@ unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b> # This is for Sola
unix &gt; <b>perl5.003 unix &gt; <b>perl5.003
use example; use example;
print example::fact(4), "\n"; print example::fact(4), "\n";
print example::my_mod(23,7), "\n"; print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n"; print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b> &lt;ctrl-d&gt;</b>
24 24
@ -279,7 +279,7 @@ Type "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; <b>import example</b> &gt;&gt;&gt; <b>import example</b>
&gt;&gt;&gt; <b>example.fact(4)</b> &gt;&gt;&gt; <b>example.fact(4)</b>
24 24
&gt;&gt;&gt; <b>example.my_mod(23,7)</b> &gt;&gt;&gt; <b>example.my_mod(23, 7)</b>
2 2
&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b> &gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
7.5 7.5
@ -303,7 +303,7 @@ unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
unix &gt; <b>perl5.003 unix &gt; <b>perl5.003
use example; use example;
print example::fact(4), "\n"; print example::fact(4), "\n";
print example::my_mod(23,7), "\n"; print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n"; print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b> &lt;ctrl-d&gt;</b>
24 24

View file

@ -563,7 +563,7 @@ Don't worry if the wrapper file doesn't exist yet--Visual Studio will keep a ref
<li>Enter "SWIG" in the description field. <li>Enter "SWIG" in the description field.
<li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field" <li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field". <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
<li>Next, select the settings for the entire project and go to C/C++ tab and select the Preprocessor category . Add the include directories to the JNI header files under "Additional include directories", eg "C:\jdk1.3\include,C:\jdk1.3\include\win32". <li>Next, select the settings for the entire project and go to C/C++ tab and select the Preprocessor category . Add the include directories to the JNI header files under "Additional include directories", eg "C:\jdk1.3\include, C:\jdk1.3\include\win32".
<li>Next, select the settings for the entire project and go to Link tab and select the General category. Set the name of the output file to match the name of your Java module (ie. example.dll). <li>Next, select the settings for the entire project and go to Link tab and select the General category. Set the name of the output file to match the name of your Java module (ie. example.dll).
<li>Next, select the example.c and example_wrap.c files and go to the C/C++ tab and select the Precompiled Headers tab in the project settings. Disabling precompiled headers for these files will overcome any precompiled header errors while building. <li>Next, select the example.c and example_wrap.c files and go to the C/C++ tab and select the Precompiled Headers tab in the project settings. Disabling precompiled headers for these files will overcome any precompiled header errors while building.
<li>Finally, add the java compilation as a post build rule in the Post-build step tab in project settings, eg, "c:\jdk1.3\bin\javac *.java" <li>Finally, add the java compilation as a post build rule in the Post-build step tab in project settings, eg, "c:\jdk1.3\bin\javac *.java"
@ -1267,7 +1267,7 @@ When wrapped, you will be able to use the functions in a natural way from Java.
<div class="code"> <div class="code">
<pre> <pre>
SWIGTYPE_p_FILE f = example.fopen("junk","w"); SWIGTYPE_p_FILE f = example.fopen("junk", "w");
example.fputs("Hello World\n", f); example.fputs("Hello World\n", f);
example.fclose(f); example.fclose(f);
</pre> </pre>
@ -1341,7 +1341,7 @@ member variables. For example,
<div class="code"><pre> <div class="code"><pre>
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -1878,7 +1878,7 @@ submodules or packages. For example, if you have a file like this,
namespace foo { namespace foo {
int fact(int n); int fact(int n);
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
}; };
</pre> </pre>
@ -1978,7 +1978,7 @@ struct pair {
~pair(); ~pair();
}; };
%template(pairii) pair&lt;int,int&gt;; %template(pairii) pair&lt;int, int&gt;;
</pre> </pre>
</div> </div>
@ -1988,7 +1988,7 @@ In Java:
<div class="code"> <div class="code">
<pre> <pre>
pairii p = new pairii(3,4); pairii p = new pairii(3, 4);
int first = p.getFirst(); int first = p.getFirst();
int second = p.getSecond(); int second = p.getSecond();
</pre> </pre>
@ -4285,11 +4285,11 @@ From Java, you could then write code like this:
<pre> <pre>
Image im = new Image(); Image im = new Image();
SWIGTYPE_p_a_4__double a = example.new_mat44(); SWIGTYPE_p_a_4__double a = example.new_mat44();
example.mat44_set(a,0,0,1.0); example.mat44_set(a, 0, 0, 1.0);
example.mat44_set(a,1,1,1.0); example.mat44_set(a, 1, 1, 1.0);
example.mat44_set(a,2,2,1.0); example.mat44_set(a, 2, 2, 1.0);
... ...
example.set_transform(im,a); example.set_transform(im, a);
example.free_mat44(a); example.free_mat44(a);
</pre> </pre>
</div> </div>
@ -4317,13 +4317,13 @@ Here is a simple example:
%} %}
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
%extend Vector { %extend Vector {
char *toString() { char *toString() {
static char tmp[1024]; static char tmp[1024];
sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z); sprintf(tmp, "Vector(%g, %g, %g)", $self-&gt;x, $self-&gt;y, $self-&gt;z);
return tmp; return tmp;
} }
Vector(double x, double y, double z) { Vector(double x, double y, double z) {
@ -4343,7 +4343,7 @@ Now, in Java
<div class="code"> <div class="code">
<pre> <pre>
Vector v = new Vector(2,3,4); Vector v = new Vector(2, 3, 4);
System.out.println(v); System.out.println(v);
</pre> </pre>
</div> </div>
@ -4354,7 +4354,7 @@ will display
<div class="code"> <div class="code">
<pre> <pre>
Vector(2,3,4) Vector(2, 3, 4)
</pre> </pre>
</div> </div>
@ -4606,10 +4606,10 @@ In Java, this allows you to pass simple values. For example:
<div class="code"> <div class="code">
<pre> <pre>
int result = example.sub(7,4); int result = example.sub(7, 4);
System.out.println("7 - 4 = " + result); System.out.println("7 - 4 = " + result);
int[] sum = {0}; int[] sum = {0};
example.add(3,4,sum); example.add(3, 4, sum);
System.out.println("3 + 4 = " + sum[0]); System.out.println("3 + 4 = " + sum[0]);
</pre> </pre>
</div> </div>
@ -4754,7 +4754,7 @@ extern void add(int x, int y, int *result);
</div> </div>
<p> <p>
The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create, The <tt>%pointer_functions(type, name)</tt> macro generates five helper functions that can be used to create,
destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows: destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows:
</p> </p>
@ -4775,20 +4775,20 @@ In Java, you would use the functions like this:
<div class="code"> <div class="code">
<pre> <pre>
SWIGTYPE_p_int intPtr = example.new_intp(); SWIGTYPE_p_int intPtr = example.new_intp();
example.add(3,4,intPtr); example.add(3, 4, intPtr);
int result = example.intp_value(intPtr); int result = example.intp_value(intPtr);
System.out.println("3 + 4 = " + result); System.out.println("3 + 4 = " + result);
</pre> </pre>
</div> </div>
<p> <p>
If you replace <tt>%pointer_functions(int,intp)</tt> by <tt>%pointer_class(int,intp)</tt>, the interface is more class-like. If you replace <tt>%pointer_functions(int, intp)</tt> by <tt>%pointer_class(int, intp)</tt>, the interface is more class-like.
</p> </p>
<div class="code"> <div class="code">
<pre> <pre>
intp intPtr = new intp(); intp intPtr = new intp();
example.add(3,4,intPtr.cast()); example.add(3, 4, intPtr.cast());
int result = intPtr.value(); int result = intPtr.value();
System.out.println("3 + 4 = " + result); System.out.println("3 + 4 = " + result);
</pre> </pre>
@ -4907,7 +4907,7 @@ int[] array = new int[10000000]; // Array of 10-million integers
for (int i=0; i&lt;array.length; i++) { // Set some values for (int i=0; i&lt;array.length; i++) { // Set some values
array[i] = i; array[i] = i;
} }
int sum = example.sumitems(array,10000); int sum = example.sumitems(array, 10000);
System.out.println("Sum = " + sum); System.out.println("Sum = " + sum);
</pre> </pre>
</div> </div>
@ -4939,7 +4939,7 @@ For example:
</div> </div>
<p> <p>
The <tt>%array_functions(type,name)</tt> macro generates four helper functions that can be used to create and The <tt>%array_functions(type, name)</tt> macro generates four helper functions that can be used to create and
destroy arrays and operate on elements. In this case, the functions are as follows: destroy arrays and operate on elements. In this case, the functions are as follows:
</p> </p>
@ -4960,15 +4960,15 @@ In Java, you would use the functions like this:
<pre> <pre>
SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers
for (int i=0; i&lt;10000; i++) { // Set some values for (int i=0; i&lt;10000; i++) { // Set some values
example.intArray_setitem(array,i,i); example.intArray_setitem(array, i, i);
} }
int sum = example.sumitems(array,10000); int sum = example.sumitems(array, 10000);
System.out.println("Sum = " + sum); System.out.println("Sum = " + sum);
</pre> </pre>
</div> </div>
<p> <p>
If you replace <tt>%array_functions(int,intp)</tt> by <tt>%array_class(int,intp)</tt>, the interface is more class-like If you replace <tt>%array_functions(int, intp)</tt> by <tt>%array_class(int, intp)</tt>, the interface is more class-like
and a couple more helper functions are available for casting between the array and the type wrapper class. and a couple more helper functions are available for casting between the array and the type wrapper class.
</p> </p>
@ -4989,9 +4989,9 @@ For instance, you will be able to do this in Java:
<pre> <pre>
intArray array = new intArray(10000000); // Array of 10-million integers intArray array = new intArray(10000000); // Array of 10-million integers
for (int i=0; i&lt;10000; i++) { // Set some values for (int i=0; i&lt;10000; i++) { // Set some values
array.setitem(i,i); array.setitem(i, i);
} }
int sum = example.sumitems(array.cast(),10000); int sum = example.sumitems(array.cast(), 10000);
System.out.println("Sum = " + sum); System.out.println("Sum = " + sum);
</pre> </pre>
</div> </div>
@ -5491,7 +5491,7 @@ parameter is omitted):
<div class="code"> <div class="code">
<pre> <pre>
int c = example.count('e',"Hello World"); int c = example.count('e', "Hello World");
</pre> </pre>
</div> </div>
@ -5814,7 +5814,7 @@ Note that when the 'pre' or 'post' attributes are specified and the associated t
<p> <p>
The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc. The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>, <tt>$result</tt> etc.
</p> </p>
<p> <p>
@ -6337,7 +6337,7 @@ For example, integers are converted as follows:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(directorin,descriptor="I") int "$input = (jint) $1;" %typemap(directorin, descriptor="I") int "$input = (jint) $1;"
</pre> </pre>
</div> </div>
@ -7072,7 +7072,7 @@ public class runme {
} }
public static void main(String argv[]) { public static void main(String argv[]) {
String animals[] = {"Cat","Dog","Cow","Goat"}; String animals[] = {"Cat", "Dog", "Cow", "Goat"};
example.print_args(animals); example.print_args(animals);
String args[] = example.get_args(); String args[] = example.get_args();
for (int i=0; i&lt;args.length; i++) for (int i=0; i&lt;args.length; i++)

View file

@ -415,7 +415,7 @@ open new windows, and many more things.
var example = require("example"); var example = require("example");
var x = 18; var x = 18;
var y = 24; var y = 24;
var z = example.gcd(x,y); var z = example.gcd(x, y);
document.querySelector('#x').innerHTML = x; document.querySelector('#x').innerHTML = x;
document.querySelector('#y').innerHTML = y; document.querySelector('#y').innerHTML = y;
document.querySelector('#z').innerHTML = z; document.querySelector('#z').innerHTML = z;
@ -467,7 +467,7 @@ var example = require("./build/Release/example");
// calling the global method // calling the global method
var x = 42; var x = 42;
var y = 105; var y = 105;
var g = example.gcd(x,y); var g = example.gcd(x, y);
// Accessing the global variable // Accessing the global variable
var f = example.Foo; var f = example.Foo;
@ -742,7 +742,7 @@ t_register.replace("$jsparent", state.clazz(NAME_MANGLED))
.trim(). .trim().
print(f_init_static_wrappers);</pre> print(f_init_static_wrappers);</pre>
</div> </div>
<p>A code template is registered with the <em>JSEmitter</em> via <code>fragment(name, &quot;template&quot;)</code>, e.g.,</p> <p>A code template is registered with the <em>JSEmitter</em> via <code>fragment(name, &quot;template&quot;)</code>, e.g., </p>
<div class="code"> <div class="code">
<pre> <pre>
%fragment ("jsc_variable_declaration", "templates") %fragment ("jsc_variable_declaration", "templates")
@ -921,7 +921,7 @@ state.clazz(NAME, Getattr(n, "sym:name"));</pre>
<p>Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.</p> <p>Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.</p>
<div class="code"> <div class="code">
<pre> <pre>
void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length) void script_exception_to_string(JSContextRef js_context, JSValueRef exception_value_ref, char* return_error_string, int return_error_string_max_length)
{ {
JSObjectRef exception_object; JSObjectRef exception_object;
JSValueRef value_ref; JSValueRef value_ref;
@ -933,7 +933,7 @@ void script_exception_to_string(JSContextRef js_context,JSValueRef exception_val
exception_object = JSValueToObject(js_context, exception_value_ref, NULL); exception_object = JSValueToObject(js_context, exception_value_ref, NULL);
/* source url */ /* source url */
strcpy(return_error_string,&quot;[&quot;); strcpy(return_error_string, &quot;[&quot;);
jsstring_property_name = JSStringCreateWithUTF8CString(&quot;sourceURL&quot;); jsstring_property_name = JSStringCreateWithUTF8CString(&quot;sourceURL&quot;);
value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception); value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
JSStringRelease(jsstring_property_name); JSStringRelease(jsstring_property_name);

View file

@ -115,7 +115,7 @@ this module is in generating pointers to primitive datatypes such as
</p> </p>
<p> <p>
<b><tt>%pointer_functions(type,name)</tt></b> <b><tt>%pointer_functions(type, name)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -195,7 +195,7 @@ Now, in Python:
<pre> <pre>
&gt;&gt;&gt; import example &gt;&gt;&gt; import example
&gt;&gt;&gt; c = example.new_intp() # Create an "int" for storing result &gt;&gt;&gt; c = example.new_intp() # Create an "int" for storing result
&gt;&gt;&gt; example.add(3,4,c) # Call function &gt;&gt;&gt; example.add(3, 4, c) # Call function
&gt;&gt;&gt; example.intp_value(c) # Dereference &gt;&gt;&gt; example.intp_value(c) # Dereference
7 7
&gt;&gt;&gt; example.delete_intp(c) # Delete &gt;&gt;&gt; example.delete_intp(c) # Delete
@ -205,7 +205,7 @@ Now, in Python:
</div> </div>
<p> <p>
<b><tt>%pointer_class(type,name)</tt></b> <b><tt>%pointer_class(type, name)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -275,7 +275,7 @@ Now, in Python (using proxy classes)
<pre> <pre>
&gt;&gt;&gt; import example &gt;&gt;&gt; import example
&gt;&gt;&gt; c = example.intp() # Create an "int" for storing result &gt;&gt;&gt; c = example.intp() # Create an "int" for storing result
&gt;&gt;&gt; example.add(3,4,c) # Call function &gt;&gt;&gt; example.add(3, 4, c) # Call function
&gt;&gt;&gt; c.value() # Dereference &gt;&gt;&gt; c.value() # Dereference
7 7
</pre> </pre>
@ -331,7 +331,7 @@ raw C array data.
</p> </p>
<p> <p>
<b><tt>%array_functions(type,name)</tt></b> <b><tt>%array_functions(type, name)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -414,8 +414,8 @@ Now, in a scripting language, you might write this:
<div class="code"> <div class="code">
<pre> <pre>
a = new_doubleArray(10) # Create an array a = new_doubleArray(10) # Create an array
for i in range(0,10): for i in range(0, 10):
doubleArray_setitem(a,i,2*i) # Set a value doubleArray_setitem(a, i, 2*i) # Set a value
print_array(a) # Pass to C print_array(a) # Pass to C
delete_doubleArray(a) # Destroy array delete_doubleArray(a) # Destroy array
</pre> </pre>
@ -424,7 +424,7 @@ delete_doubleArray(a) # Destroy array
</div> </div>
<p> <p>
<b><tt>%array_class(type,name)</tt></b> <b><tt>%array_class(type, name)</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -479,7 +479,7 @@ Allows you to do this:
<pre> <pre>
import example import example
c = example.doubleArray(10) # Create double[10] c = example.doubleArray(10) # Create double[10]
for i in range(0,10): for i in range(0, 10):
c[i] = 2*i # Assign values c[i] = 2*i # Assign values
example.print_array(c) # Pass to C example.print_array(c) # Pass to C
</pre> </pre>
@ -507,7 +507,7 @@ This module defines macros for wrapping the low-level C memory allocation functi
</p> </p>
<p> <p>
<b><tt>%malloc(type [,name=type])</tt></b> <b><tt>%malloc(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -530,7 +530,7 @@ is not a valid identifier (e.g., "<tt>int *</tt>", "<tt>double **</tt>", etc.).
</div> </div>
<p> <p>
<b><tt>%calloc(type [,name=type])</tt></b> <b><tt>%calloc(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -551,7 +551,7 @@ If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>sz</tt> is requir
</div> </div>
<p> <p>
<b><tt>%realloc(type [,name=type])</tt></b> <b><tt>%realloc(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -574,7 +574,7 @@ it holds 100 integers.
</div> </div>
<p> <p>
<b><tt>%free(type [,name=type])</tt></b> <b><tt>%free(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -590,7 +590,7 @@ void free_<em>name</em>(<em>type</em> *ptr);
</div> </div>
<p> <p>
<b><tt>%sizeof(type [,name=type])</tt></b> <b><tt>%sizeof(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -606,7 +606,7 @@ Creates the constant:
</div> </div>
<p> <p>
<b><tt>%allocators(type [,name=type])</tt></b> <b><tt>%allocators(type [, name=type])</tt></b>
</p> </p>
<div class="indent"><p> <div class="indent"><p>
@ -716,14 +716,14 @@ Python example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = intArray(10) &gt;&gt;&gt; a = intArray(10)
&gt;&gt;&gt; for i in range(0,10): &gt;&gt;&gt; for i in range(0, 10):
... a[i] = i ... a[i] = i
&gt;&gt;&gt; b = cdata(a,40) &gt;&gt;&gt; b = cdata(a, 40)
&gt;&gt;&gt; b &gt;&gt;&gt; b
'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04 '\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t' \x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
&gt;&gt;&gt; c = intArray(10) &gt;&gt;&gt; c = intArray(10)
&gt;&gt;&gt; memmove(c,b) &gt;&gt;&gt; memmove(c, b)
&gt;&gt;&gt; print c[4] &gt;&gt;&gt; print c[4]
4 4
&gt;&gt;&gt; &gt;&gt;&gt;
@ -735,7 +735,7 @@ Since the size of data is not always known, the following macro is also defined:
</p> </p>
<p> <p>
<b><tt>%cdata(type [,name=type])</tt></b> <b><tt>%cdata(type [, name=type])</tt></b>
</p> </p>
<div class="indent"> <div class="indent">
@ -855,7 +855,7 @@ Now, in the target language, you can use binary string data like this:
<div class="code"> <div class="code">
<pre> <pre>
&gt;&gt;&gt; s = "H\x00\x15eg\x09\x20" &gt;&gt;&gt; s = "H\x00\x15eg\x09\x20"
&gt;&gt;&gt; parity(s,0) &gt;&gt;&gt; parity(s, 0)
</pre> </pre>
</div> </div>
@ -920,7 +920,7 @@ implementation:
<pre> <pre>
void get_path(char *s) { void get_path(char *s) {
// Potential buffer overflow---uh, oh. // Potential buffer overflow---uh, oh.
sprintf(s,"%s/%s", base_directory, sub_directory); sprintf(s, "%s/%s", base_directory, sub_directory);
} }
... ...
// Somewhere else in the C program // Somewhere else in the C program
@ -1554,7 +1554,7 @@ To illustrate the use of this library, consider the following functions:
#include &lt;numeric&gt; #include &lt;numeric&gt;
double average(std::vector&lt;int&gt; v) { double average(std::vector&lt;int&gt; v) {
return std::accumulate(v.begin(),v.end(),0.0)/v.size(); return std::accumulate(v.begin(), v.end(), 0.0)/v.size();
} }
std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) { std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
@ -1565,8 +1565,8 @@ std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
} }
void halve_in_place(std::vector&lt;double&gt;&amp; v) { void halve_in_place(std::vector&lt;double&gt;&amp; v) {
std::transform(v.begin(),v.end(),v.begin(), std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides&lt;double&gt;(),2.0)); std::bind2nd(std::divides&lt;double&gt;(), 2.0));
} }
</pre> </pre>
</div> </div>
@ -1602,20 +1602,20 @@ Now, to illustrate the behavior in the scripting interpreter, consider this Pyth
<pre> <pre>
&gt;&gt;&gt; from example import * &gt;&gt;&gt; from example import *
&gt;&gt;&gt; iv = IntVector(4) # Create an vector&lt;int&gt; &gt;&gt;&gt; iv = IntVector(4) # Create an vector&lt;int&gt;
&gt;&gt;&gt; for i in range(0,4): &gt;&gt;&gt; for i in range(0, 4):
... iv[i] = i ... iv[i] = i
&gt;&gt;&gt; average(iv) # Call method &gt;&gt;&gt; average(iv) # Call method
1.5 1.5
&gt;&gt;&gt; average([0,1,2,3]) # Call with list &gt;&gt;&gt; average([0, 1, 2, 3]) # Call with list
1.5 1.5
&gt;&gt;&gt; half([1,2,3]) # Half a list &gt;&gt;&gt; half([1, 2, 3]) # Half a list
(0.5,1.0,1.5) (0.5, 1.0, 1.5)
&gt;&gt;&gt; halve_in_place([1,2,3]) # Oops &gt;&gt;&gt; halve_in_place([1, 2, 3]) # Oops
Traceback (most recent call last): Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ? File "&lt;stdin&gt;", line 1, in ?
TypeError: Type error. Expected _p_std__vectorTdouble_t TypeError: Type error. Expected _p_std__vectorTdouble_t
&gt;&gt;&gt; dv = DoubleVector(4) &gt;&gt;&gt; dv = DoubleVector(4)
&gt;&gt;&gt; for i in range(0,4): &gt;&gt;&gt; for i in range(0, 4):
... dv[i] = i ... dv[i] = i
&gt;&gt;&gt; halve_in_place(dv) # Ok &gt;&gt;&gt; halve_in_place(dv) # Ok
&gt;&gt;&gt; for i in dv: &gt;&gt;&gt; for i in dv:
@ -1629,7 +1629,7 @@ TypeError: Type error. Expected _p_std__vectorTdouble_t
Traceback (most recent call last): Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ? File "&lt;stdin&gt;", line 1, in ?
File "example.py", line 81, in __setitem__ File "example.py", line 81, in __setitem__
def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args) def __setitem__(*args): return apply(examplec.DoubleVector___setitem__, args)
IndexError: vector index out of range IndexError: vector index out of range
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
@ -2014,7 +2014,7 @@ For example:
try { try {
$action $action
} catch (std::out_of_range&amp; e) { } catch (std::out_of_range&amp; e) {
SWIG_exception(SWIG_IndexError,const_cast&lt;char*&gt;(e.what())); SWIG_exception(SWIG_IndexError, const_cast&lt;char*&gt;(e.what()));
} }
} }
</pre> </pre>

View file

@ -148,7 +148,7 @@ struct foo {
int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p); int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);
int func123(div_t * p,int **q[100],int r[][1000][10]); int func123(div_t * p, int **q[100], int r[][1000][10]);
void lispsort_double (int n, double * array); void lispsort_double (int n, double * array);
@ -170,11 +170,11 @@ The generated SWIG Code will be:
(cl:defmacro defanonenum (&amp;body enums) (cl:defmacro defanonenum (&amp;body enums)
"Converts anonymous enums to defconstants." "Converts anonymous enums to defconstants."
`(cl:progn ,@(cl:loop for value in enums `(cl:progn , @(cl:loop for value in enums
for index = 0 then (cl:1+ index) for index = 0 then (cl:1+ index)
when (cl:listp value) do (cl:setf index (cl:second value) when (cl:listp value) do (cl:setf index (cl:second value)
value (cl:first value)) value (cl:first value))
collect `(cl:defconstant ,value ,index)))) collect `(cl:defconstant , value , index))))
(cl:eval-when (:compile-toplevel :load-toplevel) (cl:eval-when (:compile-toplevel :load-toplevel)
(cl:unless (cl:fboundp 'swig-lispify) (cl:unless (cl:fboundp 'swig-lispify)
@ -280,7 +280,7 @@ Let's edit the interface file such that the C type "div_t*" is changed
%typemap(cin) div_t* ":my-pointer"; %typemap(cin) div_t* ":my-pointer";
%feature("intern_function","1"); %feature("intern_function", "1");
%feature("export"); %feature("export");
%feature("inline") lispsort_double; %feature("inline") lispsort_double;
@ -305,7 +305,7 @@ The <i>typemap(cin)</i> ensures that for all arguments which are input
The feature <i>intern_function</i> ensures that all C names are The feature <i>intern_function</i> ensures that all C names are
interned using the <b>swig-lispify</b> function. The "1" given interned using the <b>swig-lispify</b> function. The "1" given
to the feature is optional. The use of feature like to the feature is optional. The use of feature like
<i>%feature("intern_function","1");</i> globally enables <i>%feature("intern_function", "1");</i> globally enables
interning for everything. If you want to target a single interning for everything. If you want to target a single
function, or declaration then use the targeted version of function, or declaration then use the targeted version of
feature, <i>%feature("intern_function", "my-lispify") feature, <i>%feature("intern_function", "my-lispify")
@ -722,7 +722,7 @@ The ffi wrappers for functions and variables are generated as shown
extern "C" { extern "C" {
int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y); int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);
int func123(div_t * x,int **z[100],int y[][1000][10]); int func123(div_t * x, int **z[100], int y[][1000][10]);
void lispsort_double (int n, double * array); void lispsort_double (int n, double * array);

View file

@ -193,27 +193,27 @@ Normally Lua is embedded into another program and will be statically linked. An
extern int luaopen_example(lua_State* L); // declare the wrapped module extern int luaopen_example(lua_State* L); // declare the wrapped module
int main(int argc,char* argv[]) int main(int argc, char* argv[])
{ {
lua_State *L; lua_State *L;
if (argc&lt;2) if (argc&lt;2)
{ {
printf("%s: &lt;filename.lua&gt;\n",argv[0]); printf("%s: &lt;filename.lua&gt;\n", argv[0]);
return 0; return 0;
} }
L=lua_open(); L=lua_open();
luaopen_base(L); // load basic libs (eg. print) luaopen_base(L); // load basic libs (eg. print)
luaopen_example(L); // load the wrapped module luaopen_example(L); // load the wrapped module
if (luaL_loadfile(L,argv[1])==0) // load and run the file if (luaL_loadfile(L, argv[1])==0) // load and run the file
lua_pcall(L,0,0,0); lua_pcall(L, 0, 0, 0);
else else
printf("unable to load %s\n",argv[1]); printf("unable to load %s\n", argv[1]);
lua_close(L); lua_close(L);
return 0; return 0;
} }
</pre></div> </pre></div>
<p> <p>
A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place. A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example", luaopen_example}</tt>, at the relevant place.
</p> </p>
<p> <p>
The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this: The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
@ -272,8 +272,8 @@ require("example")
For those using Lua 5.0.x, you will also need an interpreter with the loadlib function (such as the default interpreter compiled with Lua). In order to dynamically load a module you must call the loadlib function with two parameters: the filename of the shared library, and the function exported by SWIG. Calling loadlib should return the function, which you then call to initialise the module For those using Lua 5.0.x, you will also need an interpreter with the loadlib function (such as the default interpreter compiled with Lua). In order to dynamically load a module you must call the loadlib function with two parameters: the filename of the shared library, and the function exported by SWIG. Calling loadlib should return the function, which you then call to initialise the module
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux my_init=loadlib("example.so", "luaopen_example") -- for Unix/Linux
--my_init=loadlib("example.dll","luaopen_example") -- for Windows --my_init=loadlib("example.dll", "luaopen_example") -- for Windows
assert(my_init) -- make sure it's not nil assert(my_init) -- make sure it's not nil
my_init() -- call the init fn of the lib my_init() -- call the init fn of the lib
</pre></div> </pre></div>
@ -281,7 +281,7 @@ my_init() -- call the init fn of the lib
Or can be done in a single line of Lua code Or can be done in a single line of Lua code
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
assert(loadlib("example.so","luaopen_example"))() assert(loadlib("example.so", "luaopen_example"))()
</pre></div> </pre></div>
@ -289,9 +289,9 @@ assert(loadlib("example.so","luaopen_example"))()
If the code didn't work, don't panic. The best thing to do is to copy the module and your interpreter into a single directory and then execute the interpreter and try to manually load the module (take care, all this code is case sensitive). If the code didn't work, don't panic. The best thing to do is to copy the module and your interpreter into a single directory and then execute the interpreter and try to manually load the module (take care, all this code is case sensitive).
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
a,b,c=package.loadlib("example.so","luaopen_example") -- for Unix/Linux a, b, c=package.loadlib("example.so", "luaopen_example") -- for Unix/Linux
--a,b,c=package.loadlib("example.dll","luaopen_example") -- for Windows --a, b, c=package.loadlib("example.dll", "luaopen_example") -- for Windows
print(a,b,c) print(a, b, c)
</pre></div> </pre></div>
<p> <p>
Note: for Lua 5.0:<br> Note: for Lua 5.0:<br>
@ -326,7 +326,7 @@ Assuming all goes well, you will be able to this:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
$ ./my_lua $ ./my_lua
&gt; print(example.gcd(4,6)) &gt; print(example.gcd(4, 6))
2 2
&gt; print(example.Foo) &gt; print(example.Foo)
3 3
@ -373,7 +373,7 @@ This can easily overwrite existing functions, so this must be used with care.
This option is considered deprecated and will be removed in the near future. This option is considered deprecated and will be removed in the near future.
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; for k,v in pairs(example) do _G[k]=v end &gt; for k, v in pairs(example) do _G[k]=v end
&gt; print(fact(4)) &gt; print(fact(4))
24 24
&gt; &gt;
@ -411,7 +411,7 @@ SWIG will effectively generate two functions <tt>example.Foo_set()</tt> and <tt>
&gt; print(c) &gt; print(c)
3 3
&gt; c=5 -- this will not effect the original example.Foo &gt; c=5 -- this will not effect the original example.Foo
&gt; print(example.Foo,c) &gt; print(example.Foo, c)
4 5 4 5
</pre></div> </pre></div>
<p> <p>
@ -486,7 +486,7 @@ Because Lua doesn't really have the concept of constants, C/C++ constants are no
<div class="code"><pre>%module example <div class="code"><pre>%module example
%constant int ICONST=42; %constant int ICONST=42;
#define SCONST "Hello World" #define SCONST "Hello World"
enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY}; enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre></div> </pre></div>
<p> <p>
This is 'effectively' converted into the following Lua code: This is 'effectively' converted into the following Lua code:
@ -584,8 +584,8 @@ int fclose(FILE *);
When wrapped, you will be able to use the functions in a natural way from Lua. For example: When wrapped, you will be able to use the functions in a natural way from Lua. For example:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; f=example.fopen("junk","w") &gt; f=example.fopen("junk", "w")
&gt; example.fputs("Hello World",f) &gt; example.fputs("Hello World", f)
&gt; example.fclose(f) &gt; example.fclose(f)
</pre></div> </pre></div>
<p> <p>
@ -601,7 +601,7 @@ FILE * -- it's a FILE*
Lua enforces the integrity of its userdata, so it is virtually impossible to corrupt the data. But as the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes &amp; structs (see below). One final note: if a function returns a NULL pointer, this is not encoded as a userdata, but as a Lua nil. Lua enforces the integrity of its userdata, so it is virtually impossible to corrupt the data. But as the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes &amp; structs (see below). One final note: if a function returns a NULL pointer, this is not encoded as a userdata, but as a Lua nil.
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; f=example.fopen("not there","r") -- this will return a NULL in C &gt; f=example.fopen("not there", "r") -- this will return a NULL in C
&gt; print(f) &gt; print(f)
nil nil
</pre></div> </pre></div>
@ -613,7 +613,7 @@ nil
If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example, If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example,
</p> </p>
<div class="code"><pre>struct Point{ <div class="code"><pre>struct Point{
int x,y; int x, y;
}; };
</pre></div> </pre></div>
<p> <p>
@ -623,7 +623,7 @@ is used as follows:
&gt; p=example.new_Point() &gt; p=example.new_Point()
&gt; p.x=3 &gt; p.x=3
&gt; p.y=5 &gt; p.y=5
&gt; print(p.x,p.y) &gt; print(p.x, p.y)
3 5 3 5
&gt; &gt;
</pre></div> </pre></div>
@ -953,8 +953,8 @@ public:
When wrapped, it works like you expect: When wrapped, it works like you expect:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; c = Complex(3,4) &gt; c = Complex(3, 4)
&gt; d = Complex(7,8) &gt; d = Complex(7, 8)
&gt; e = c + d &gt; e = c + d
&gt; e:re() &gt; e:re()
10.0 10.0
@ -1000,18 +1000,18 @@ The current list of operators which can be overloaded (and the alternative funct
<li><tt>__le__</tt> operator<tt>&lt;=</tt> <li><tt>__le__</tt> operator<tt>&lt;=</tt>
</ul> </ul>
<p> <p>
Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=,&gt;,&gt;=) are achieved by using a logical not applied to the results of other operators. Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=, &gt;, &gt;=) are achieved by using a logical not applied to the results of other operators.
</p> </p>
<p> <p>
The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul> The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
<li>++ and --<li>+=,-=,*= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul> <li>++ and --<li>+=, -=, *= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
<p> <p>
SWIG also accepts the <tt>__str__()</tt> member function which converts an object to a string. This function should return a const char*, preferably to static memory. This will be used for the <tt>print()</tt> and <tt>tostring()</tt> functions in Lua. Assuming the complex class has a function SWIG also accepts the <tt>__str__()</tt> member function which converts an object to a string. This function should return a const char*, preferably to static memory. This will be used for the <tt>print()</tt> and <tt>tostring()</tt> functions in Lua. Assuming the complex class has a function
</p> </p>
<div class="code"><pre>const char* __str__() <div class="code"><pre>const char* __str__()
{ {
static char buffer[255]; static char buffer[255];
sprintf(buffer,"Complex(%g,%g)",this-&gt;re(),this-&gt;im()); sprintf(buffer, "Complex(%g, %g)", this-&gt;re(), this-&gt;im());
return buffer; return buffer;
} }
</pre></div> </pre></div>
@ -1019,14 +1019,14 @@ SWIG also accepts the <tt>__str__()</tt> member function which converts an objec
Then this will support the following code in Lua Then this will support the following code in Lua
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; c = Complex(3,4) &gt; c = Complex(3, 4)
&gt; d = Complex(7,8) &gt; d = Complex(7, 8)
&gt; e = c + d &gt; e = c + d
&gt; print(e) &gt; print(e)
Complex(10,12) Complex(10, 12)
&gt; s=tostring(e) -- s is the number in string form &gt; s=tostring(e) -- s is the number in string form
&gt; print(s) &gt; print(s)
Complex(10,12) Complex(10, 12)
</pre></div> </pre></div>
<p> <p>
It is also possible to overload the operator<tt>[]</tt>, but currently this cannot be automatically performed. To overload the operator<tt>[]</tt> you need to provide two functions, <tt>__getitem__()</tt> and <tt>__setitem__()</tt> It is also possible to overload the operator<tt>[]</tt>, but currently this cannot be automatically performed. To overload the operator<tt>[]</tt> you need to provide two functions, <tt>__getitem__()</tt> and <tt>__setitem__()</tt>
@ -1035,7 +1035,7 @@ It is also possible to overload the operator<tt>[]</tt>, but currently this cann
{ {
//.... //....
double __getitem__(int i)const; // i is the index, returns the data double __getitem__(int i)const; // i is the index, returns the data
void __setitem__(int i,double d); // i is the index, d is the data void __setitem__(int i, double d); // i is the index, d is the data
}; };
</pre></div> </pre></div>
<p> <p>
@ -1092,7 +1092,7 @@ Now we extend it with some new code
<div class="code"><pre>%extend Complex { <div class="code"><pre>%extend Complex {
const char *__str__() { const char *__str__() {
static char tmp[1024]; static char tmp[1024];
sprintf(tmp,"Complex(%g,%g)", $self-&gt;re(),$self-&gt;im()); sprintf(tmp, "Complex(%g, %g)", $self-&gt;re(), $self-&gt;im());
return tmp; return tmp;
} }
bool operator==(const Complex&amp; c) { bool operator==(const Complex&amp; c) {
@ -1104,14 +1104,14 @@ Now we extend it with some new code
Now, in Lua Now, in Lua
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; c = Complex(3,4) &gt; c = Complex(3, 4)
&gt; d = Complex(7,8) &gt; d = Complex(7, 8)
&gt; e = c + d &gt; e = c + d
&gt; print(e) -- print uses __str__ to get the string form to print &gt; print(e) -- print uses __str__ to get the string form to print
Complex(10,12) Complex(10, 12)
&gt; print(e==Complex(10,12)) -- testing the == operator &gt; print(e==Complex(10, 12)) -- testing the == operator
true true
&gt; print(e!=Complex(12,12)) -- the != uses the == operator &gt; print(e!=Complex(12, 12)) -- the != uses the == operator
true true
</pre></div> </pre></div>
<p> <p>
@ -1121,7 +1121,7 @@ Extend works with both C and C++ code, on classes and structs. It does not modif
<H3><a name="Lua_nn20">28.3.13 Using %newobject to release memory</a></H3> <H3><a name="Lua_nn20">28.3.13 Using %newobject to release memory</a></H3>
<p> If you have a function that allocates memory like this,</p> <p> If you have a function that allocates memory like this, </p>
<div class="code"> <div class="code">
<pre>char *foo() { <pre>char *foo() {
char *result = (char *) malloc(...); char *result = (char *) malloc(...);
@ -1164,14 +1164,14 @@ struct pair {
~pair(); ~pair();
}; };
%template(pairii) pair&lt;int,int&gt;; %template(pairii) pair&lt;int, int&gt;;
</pre></div> </pre></div>
<p> <p>
In Lua: In Lua:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; p = example.pairii(3,4) &gt; p = example.pairii(3, 4)
&gt; print(p.first,p.second) &gt; print(p.first, p.second)
3 4 3 4
</pre></div> </pre></div>
<p> <p>
@ -1265,11 +1265,11 @@ Using xpcall will allow you to obtain additional debug information (such as a st
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; function a() b() end -- function a() calls function b() &gt; function a() b() end -- function a() calls function b()
&gt; function b() message() end -- function b() calls C++ function message(), which throws &gt; function b() message() end -- function b() calls C++ function message(), which throws
&gt; ok,res=pcall(a) -- call the function &gt; ok, res=pcall(a) -- call the function
&gt; print(ok,res) &gt; print(ok, res)
false I died. false I died.
&gt; ok,res=xpcall(a,debug.traceback) -- call the function &gt; ok, res=xpcall(a, debug.traceback) -- call the function
&gt; print(ok,res) &gt; print(ok, res)
false I died. false I died.
stack traceback: stack traceback:
[C]: in function 'message' [C]: in function 'message'
@ -1322,7 +1322,7 @@ If you have your own class which you want output as a string you will need to ad
<div class="code"><pre> <div class="code"><pre>
%typemap(throws) my_except %typemap(throws) my_except
%{ %{
lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message lua_pushstring(L, $1.what()); // assuming my_except::what() returns a const char* message
SWIG_fail; // trigger the error handler SWIG_fail; // trigger the error handler
%} %}
</pre></div> </pre></div>
@ -1337,26 +1337,26 @@ class Exc {
public: public:
Exc(int c, const char *m) { Exc(int c, const char *m) {
code = c; code = c;
strncpy(msg,m,256); strncpy(msg, m, 256);
} }
int code; int code;
char msg[256]; char msg[256];
}; };
void throw_exc() throw(Exc) { void throw_exc() throw(Exc) {
throw(Exc(42,"Hosed")); throw(Exc(42, "Hosed"));
} }
</pre></div> </pre></div>
<p> <p>
Then the following code can be used (note: we use pcall to catch the error so we can process the exception). Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt; ok,res=pcall(throw_exc) &gt; ok, res=pcall(throw_exc)
&gt; print(ok) &gt; print(ok)
false false
&gt; print(res) &gt; print(res)
userdata: 0003D880 userdata: 0003D880
&gt; print(res.code,res.msg) &gt; print(res.code, res.msg)
42 Hosed 42 Hosed
&gt; &gt;
</pre></div> </pre></div>
@ -1537,8 +1537,8 @@ function
<div class="code"><pre>%module example <div class="code"><pre>%module example
%typemap(in) int { %typemap(in) int {
$1 = (int) lua_tonumber(L,$input); $1 = (int) lua_tonumber(L, $input);
printf("Received an integer : %d\n",$1); printf("Received an integer : %d\n", $1);
} }
%inline %{ %inline %{
extern int fact(int n); extern int fact(int n);
@ -1596,13 +1596,13 @@ void swap(int *sx, int *sy);
<p>When wrapped, it gives the following results:</p> <p>When wrapped, it gives the following results:</p>
<div class="targetlang"><pre>&gt; require "example" <div class="targetlang"><pre>&gt; require "example"
&gt; print(example.add(1,2)) &gt; print(example.add(1, 2))
3 3
&gt; print(demo.sub(1,2)) &gt; print(demo.sub(1, 2))
-1 -1
&gt; a,b=1,2 &gt; a, b=1, 2
&gt; c,d=demo.swap(a,b) &gt; c, d=demo.swap(a, b)
&gt; print(a,b,c,d) &gt; print(a, b, c, d)
1 2 2 1 1 2 2 1
</pre></div> </pre></div>
@ -1633,13 +1633,13 @@ More details can be found in the <a href="Library.html#Library_carrays">carrays.
<div class="code"><pre>// using the C-array <div class="code"><pre>// using the C-array
%include &lt;carrays.i&gt; %include &lt;carrays.i&gt;
// this declares a batch of function for manipulating C integer arrays // this declares a batch of function for manipulating C integer arrays
%array_functions(int,int) %array_functions(int, int)
extern void sort_int(int* arr, int len); // the function to wrap extern void sort_int(int* arr, int len); // the function to wrap
// using typemaps // using typemaps
%include &lt;typemaps.i&gt; %include &lt;typemaps.i&gt;
%apply (double *INOUT,int) {(double* arr,int len)}; %apply (double *INOUT, int) {(double* arr, int len)};
extern void sort_double(double* arr, int len); // the function to wrap extern void sort_double(double* arr, int len); // the function to wrap
</pre></div> </pre></div>
@ -1651,16 +1651,16 @@ ARRAY_SIZE=10
-- passing a C array to the sort_int() -- passing a C array to the sort_int()
arr=example.new_int(ARRAY_SIZE) -- create the array arr=example.new_int(ARRAY_SIZE) -- create the array
for i=0,ARRAY_SIZE-1 do -- index 0..9 (just like C) for i=0, ARRAY_SIZE-1 do -- index 0..9 (just like C)
example.int_setitem(arr,i,math.random(1000)) example.int_setitem(arr, i, math.random(1000))
end end
example.sort_int(arr,ARRAY_SIZE) -- call the function example.sort_int(arr, ARRAY_SIZE) -- call the function
example.delete_int(arr) -- must delete the allocated memory example.delete_int(arr) -- must delete the allocated memory
-- use a typemap to call with a Lua-table -- use a typemap to call with a Lua-table
-- one item of note: the typemap creates a copy, rather than edit-in-place -- one item of note: the typemap creates a copy, rather than edit-in-place
t={} -- a Lua table t={} -- a Lua table
for i=1,ARRAY_SIZE do -- index 1..10 (Lua style) for i=1, ARRAY_SIZE do -- index 1..10 (Lua style)
t[i]=math.random(1000)/10 t[i]=math.random(1000)/10
end end
t=example.sort_double(t) -- replace t with the result t=example.sort_double(t) -- replace t with the result
@ -1704,7 +1704,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs)
<p>The usage is as follows:</p> <p>The usage is as follows:</p>
<div class="targetlang"><pre>ok,ptr=Create_Math() -- ptr is an iMath* which is returned with the int (ok) <div class="targetlang"><pre>ok, ptr=Create_Math() -- ptr is an iMath* which is returned with the int (ok)
ptr=nil -- the iMath* will be GC'ed as normal ptr=nil -- the iMath* will be GC'ed as normal
</pre></div> </pre></div>
@ -1735,7 +1735,7 @@ ptr=nil -- the iMath* will be GC'ed as normal
<p>This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.</p> <p>This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.</p>
<p><tt>int SWIG_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags);</tt></p> <p><tt>int SWIG_ConvertPtr(lua_State* L, int index, void** ptr, swig_type_info *type, int flags);</tt></p>
<div class="indent"> <div class="indent">
This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the necessary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer. This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the necessary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer.
@ -1743,14 +1743,14 @@ If flags is set to SWIG_POINTER_DISOWN, this is will clear any ownership flag se
This returns a value which can be checked with the macro SWIG_IsOK() This returns a value which can be checked with the macro SWIG_IsOK()
</div> </div>
<p><tt>void SWIG_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type,int own);</tt></p> <p><tt>void SWIG_NewPointerObj(lua_State* L, void* ptr, swig_type_info *type, int own);</tt></p>
<div class="indent"> <div class="indent">
This is the opposite of SWIG_ConvertPtr, as it pushes a new userdata which wrappers the pointer 'ptr' of type 'type'. This is the opposite of SWIG_ConvertPtr, as it pushes a new userdata which wrappers the pointer 'ptr' of type 'type'.
The parameter 'own' specifies if the object is owned be Lua and if it is 1 then Lua will GC the object when the userdata is disposed of. The parameter 'own' specifies if the object is owned be Lua and if it is 1 then Lua will GC the object when the userdata is disposed of.
</div> </div>
<p><tt>void* SWIG_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags,int argnum,const char* func_name);</tt></p> <p><tt>void* SWIG_MustGetPtr(lua_State* L, int index, swig_type_info *type, int flags, int argnum, const char* func_name);</tt></p>
<div class="indent"> <div class="indent">
This function is a version of SWIG_ConvertPtr(), except that it will either work, or it will trigger a lua_error() with a text error message. This function is rarely used, and may be deprecated in the future. This function is a version of SWIG_ConvertPtr(), except that it will either work, or it will trigger a lua_error() with a text error message. This function is rarely used, and may be deprecated in the future.
@ -1762,11 +1762,11 @@ This function is a version of SWIG_ConvertPtr(), except that it will either work
This macro, when called within the context of a SWIG wrapped function, will jump to the error handler code. This will call any cleanup code (freeing any temp variables) and then triggers a lua_error.<br> This macro, when called within the context of a SWIG wrapped function, will jump to the error handler code. This will call any cleanup code (freeing any temp variables) and then triggers a lua_error.<br>
A common use for this code is:<br><pre> A common use for this code is:<br><pre>
if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){ if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
lua_pushstring(L,"something bad happened"); lua_pushstring(L, "something bad happened");
SWIG_fail; SWIG_fail;
}</pre></div> }</pre></div>
<p><tt>SWIG_fail_arg(char* func_name,int argnum,char* type)</tt></p> <p><tt>SWIG_fail_arg(char* func_name, int argnum, char* type)</tt></p>
<div class="indent"> <div class="indent">
This macro, when called within the context of a SWIG wrapped function, will display the error message and jump to the error handler code. The error message is of the form This macro, when called within the context of a SWIG wrapped function, will display the error message and jump to the error handler code. The error message is of the form
@ -1774,7 +1774,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
"Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'" "Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'"
</pre></div> </pre></div>
<p><tt>SWIG_fail_ptr(const char* fn_name,int argnum,swig_type_info* type);</tt></p> <p><tt>SWIG_fail_ptr(const char* fn_name, int argnum, swig_type_info* type);</tt></p>
<div class="indent"> <div class="indent">
Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.</div> Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.</div>
@ -1878,24 +1878,24 @@ At initialisation time, it will then add to the interpreter a table called 'exam
&gt; print(example) &gt; print(example)
table: 003F8F90 table: 003F8F90
&gt; m=getmetatable(example) &gt; m=getmetatable(example)
&gt; table.foreach(m,print) &gt; table.foreach(m, print)
.set table: 003F9088 .set table: 003F9088
.get table: 003F9038 .get table: 003F9038
__index function: 003F8FE0 __index function: 003F8FE0
__newindex function: 003F8FF8 __newindex function: 003F8FF8
&gt; g=m['.get'] &gt; g=m['.get']
&gt; table.foreach(g,print) &gt; table.foreach(g, print)
Foo function: 003FAFD8 Foo function: 003FAFD8
&gt; &gt;
</pre></div> </pre></div>
<p> <p>
The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get) The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set, Foo_get)
</p> </p>
<p> <p>
The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
function __index(mod,name) function __index(mod, name)
local g=getmetatable(mod)['.get'] -- gets the table local g=getmetatable(mod)['.get'] -- gets the table
if not g then return nil end if not g then return nil end
local f=g[name] -- looks for the function local f=g[name] -- looks for the function
@ -1904,13 +1904,13 @@ function __index(mod,name)
return nil return nil
end end
function __newindex(mod,name,value) function __newindex(mod, name, value)
local s=getmetatable(mod)['.set'] -- gets the table local s=getmetatable(mod)['.set'] -- gets the table
if not s then return end if not s then return end
local f=s[name] -- looks for the function local f=s[name] -- looks for the function
-- calls it to set the value -- calls it to set the value
if type(f)=="function" then f(value) if type(f)=="function" then f(value)
else rawset(mod,name,value) end else rawset(mod, name, value) end
end end
</pre></div> </pre></div>
<p> <p>
@ -1933,10 +1933,10 @@ Given a class
class Point class Point
{ {
public: public:
int x,y; int x, y;
Point(){x=y=0;} Point(){x=y=0;}
~Point(){} ~Point(){}
virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);} virtual void Print(){printf("Point @%p (%d, %d)\n", this, x, y);}
}; };
</pre></div> </pre></div>
<p> <p>
@ -1950,7 +1950,7 @@ Some of the internals can be seen by looking at the metatable of a class:
&gt; print(p) &gt; print(p)
userdata: 003FDB28 userdata: 003FDB28
&gt; m=getmetatable(p) &gt; m=getmetatable(p)
&gt; table.foreach(m,print) &gt; table.foreach(m, print)
.type Point .type Point
__gc function: 003FB6C8 __gc function: 003FB6C8
__newindex function: 003FB6B0 __newindex function: 003FB6B0
@ -1966,7 +1966,7 @@ The '.type' attribute is the name of the class. The '.get' and '.set' tables wor
The Lua equivalent of the code for enabling functions looks a little like this The Lua equivalent of the code for enabling functions looks a little like this
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
function __index(obj,name) function __index(obj, name)
local m=getmetatable(obj) -- gets the metatable local m=getmetatable(obj) -- gets the metatable
if not m then return nil end if not m then return nil end
local g=m['.get'] -- gets the attribute table local g=m['.get'] -- gets the attribute table

View file

@ -684,7 +684,7 @@ consist of the following parts:
</tr> </tr>
<tr> <tr>
<td>m3wrapfreearg</td> <td>m3wrapfreearg</td>
<td><tt>M3toC.FreeSharedS(str,arg1);</tt></td> <td><tt>M3toC.FreeSharedS(str, arg1);</tt></td>
<td> <td>
Free resources that were temporarily used in the wrapper. Free resources that were temporarily used in the wrapper.
Since this step should never be skipped, Since this step should never be skipped,
@ -858,7 +858,7 @@ where almost everything is generated by a typemap:
RAISE E("invalid checksum"); RAISE E("invalid checksum");
END; END;
FINALLY FINALLY
M3toC.FreeSharedS(str,arg1); <I>(* m3wrapfreearg *)</I> M3toC.FreeSharedS(str, arg1); <I>(* m3wrapfreearg *)</I>
END; END;
END Name; END Name;
</pre></div> </pre></div>
@ -891,7 +891,7 @@ where almost everything is generated by a typemap:
<tr> <tr>
<td>constnumeric</td> <td>constnumeric</td>
<td><tt>%constnumeric(12) twelve;</tt> or <td><tt>%constnumeric(12) twelve;</tt> or
<tt>%feature("constnumeric","12") twelve;</tt></td> <tt>%feature("constnumeric", "12") twelve;</tt></td>
<td>This feature can be used to tell Modula-3's back-end of SWIG <td>This feature can be used to tell Modula-3's back-end of SWIG
the value of an identifier. the value of an identifier.
This is necessary in the cases This is necessary in the cases

View file

@ -44,7 +44,7 @@ The general form of this directive is:
</p> </p>
<div class="code"><pre> <div class="code"><pre>
<tt>%module(option1="value1",option2="value2",...) modulename</tt> <tt>%module(option1="value1", option2="value2", ...) modulename</tt>
</pre></div> </pre></div>
<p> <p>

View file

@ -34,13 +34,13 @@ Example interface file:
<div class="code"> <div class="code">
<pre> <pre>
/* define a macro for the struct creation */ /* define a macro for the struct creation */
%define handle_ptr(TYPE,NAME) %define handle_ptr(TYPE, NAME)
%typemap(argout) TYPE *NAME{ %typemap(argout) TYPE *NAME{
Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle); Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
SWIG_APPEND_VALUE(o); SWIG_APPEND_VALUE(o);
} }
%typemap(in,numinputs=0) TYPE *NAME (TYPE temp) { %typemap(in, numinputs=0) TYPE *NAME (TYPE temp) {
$1 = &amp;temp; $1 = &amp;temp;
} }
%enddef %enddef

View file

@ -90,7 +90,7 @@ If you're not familiar with the Objective Caml language, you can visit
<p> <p>
SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice,
you should use the latest stable release. The SWIG Ocaml module has you should use the latest stable release. The SWIG Ocaml module has
been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The been tested on Linux (x86, PPC, Sparc) and Cygwin on Windows. The
best way to determine whether your system will work is to compile the best way to determine whether your system will work is to compile the
examples and test-suite which come with SWIG. You can do this by running examples and test-suite which come with SWIG. You can do this by running
<tt>make check</tt> from the SWIG root directory after installing SWIG. <tt>make check</tt> from the SWIG root directory after installing SWIG.
@ -327,7 +327,7 @@ A few functions exist which generate and return these:
Because of this style, a typemap can return any kind of value it Because of this style, a typemap can return any kind of value it
wants from a function. This enables out typemaps and inout typemaps wants from a function. This enables out typemaps and inout typemaps
to work well. The one thing to remember about outputting values to work well. The one thing to remember about outputting values
is that you must append them to the return list with swig_result = caml_list_append(swig_result,v). is that you must append them to the return list with swig_result = caml_list_append(swig_result, v).
</p> </p>
<p> <p>
@ -505,7 +505,7 @@ Unfortunately, unbounded arrays and pointers can't be handled in a
completely general way by SWIG, because the end-condition of such an completely general way by SWIG, because the end-condition of such an
array can't be predicted. In some cases, it will be by consent array can't be predicted. In some cases, it will be by consent
(e.g. an array of four or more chars), sometimes by explicit length (e.g. an array of four or more chars), sometimes by explicit length
(char *buffer, int len), and sometimes by sentinel value (0,-1,etc.). (char *buffer, int len), and sometimes by sentinel value (0, -1, etc.).
SWIG can't predict which of these methods will be used in the array, SWIG can't predict which of these methods will be used in the array,
so you have to specify it for yourself in the form of a typemap. so you have to specify it for yourself in the form of a typemap.
</p> </p>
@ -560,7 +560,7 @@ void printfloats( float *tab, int len ) {
$2 = caml_array_len($input); $2 = caml_array_len($input);
$1 = ($*1_type *)malloc( $2 * sizeof( float ) ); $1 = ($*1_type *)malloc( $2 * sizeof( float ) );
for( i = 0; i &lt; $2; i++ ) { for( i = 0; i &lt; $2; i++ ) {
$1[i] = caml_double_val(caml_array_nth($input,i)); $1[i] = caml_double_val(caml_array_nth($input, i));
} }
} }
@ -684,7 +684,7 @@ C_list
- : Example.c_obj = C_void - : Example.c_obj = C_void
# x '[1] ;; # x '[1] ;;
- : Example.c_obj = C_string "bar" - : Example.c_obj = C_string "bar"
# x -&gt; set (1,"spam") ;; # x -&gt; set (1, "spam") ;;
- : Example.c_obj = C_void - : Example.c_obj = C_void
# x '[1] ;; # x '[1] ;;
- : Example.c_obj = C_string "spam" - : Example.c_obj = C_string "spam"
@ -757,11 +757,11 @@ bash-2.05a$ ./qt_top
# open Swig ;; # open Swig ;;
# open Qt ;; # open Qt ;;
# let a = new_QApplication '(0,0) ;; # let a = new_QApplication '(0, 0) ;;
val a : Qt.c_obj = C_obj &lt;fun&gt; val a : Qt.c_obj = C_obj &lt;fun&gt;
# let hello = new_QPushButton '("hi",0) ;; # let hello = new_QPushButton '("hi", 0) ;;
val hello : Qt.c_obj = C_obj &lt;fun&gt; val hello : Qt.c_obj = C_obj &lt;fun&gt;
# hello -&gt; resize (100,30) ;; # hello -&gt; resize (100, 30) ;;
- : Qt.c_obj = C_void - : Qt.c_obj = C_void
# hello -&gt; show () ;; # hello -&gt; show () ;;
- : Qt.c_obj = C_void - : Qt.c_obj = C_void
@ -857,7 +857,7 @@ let triangle_class pts ob meth args =
let triangle = let triangle =
new_derived_object new_derived_object
new_shape new_shape
(triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
'() ;; '() ;;
let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;; let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
@ -901,7 +901,7 @@ The definition of the actual object triangle can be described this way:
let triangle = let triangle =
new_derived_object new_derived_object
new_shape new_shape
(triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
'() '()
</pre></div> </pre></div>

View file

@ -161,7 +161,7 @@ Assuming all goes well, you will be able to do this:
<div class="targetlang"><pre>$ octave -q <div class="targetlang"><pre>$ octave -q
octave:1&gt; swigexample octave:1&gt; swigexample
octave:2&gt; swigexample.gcd(4,6) octave:2&gt; swigexample.gcd(4, 6)
ans = 2 ans = 2
octave:3&gt; swigexample.cvar.Foo octave:3&gt; swigexample.cvar.Foo
ans = 3 ans = 3
@ -189,7 +189,7 @@ To load an Octave module, simply type its name:
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; swigexample; octave:1&gt; swigexample;
octave:2&gt; gcd(4,6) octave:2&gt; gcd(4, 6)
ans = 2 ans = 2
octave:3&gt; cvar.Foo octave:3&gt; cvar.Foo
ans = 3 ans = 3
@ -204,16 +204,16 @@ If the module is also used in the base context, however, it must first be loaded
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; function l = my_lcm(a,b) octave:1&gt; function l = my_lcm(a, b)
&gt; swigexample &gt; swigexample
&gt; l = abs(a*b)/swigexample.gcd(a,b); &gt; l = abs(a*b)/swigexample.gcd(a, b);
&gt; endfunction &gt; endfunction
octave:2&gt; my_lcm(4,6) octave:2&gt; my_lcm(4, 6)
ans = 12 ans = 12
octave:3&gt; swigexample.gcd(4,6) octave:3&gt; swigexample.gcd(4, 6)
error: can't perform indexing operations for &lt;unknown type&gt; type error: can't perform indexing operations for &lt;unknown type&gt; type
octave:3&gt; swigexample; octave:3&gt; swigexample;
octave:4&gt; swigexample.gcd(4,6) octave:4&gt; swigexample.gcd(4, 6)
ans = 2 ans = 2
</pre></div> </pre></div>
@ -297,7 +297,7 @@ ans = 3.1420 </pre></div>
<div class="code"><pre>%module swigexample <div class="code"><pre>%module swigexample
%constant int ICONST=42; %constant int ICONST=42;
#define SCONST "Hello World" #define SCONST "Hello World"
enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY}; enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre></div> </pre></div>
<p> <p>
@ -329,8 +329,8 @@ When wrapped, you will be able to use the functions in a natural way from Octave
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; swigexample; octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("w","junk"); octave:2&gt; f=swigexample.fopen("w", "junk");
octave:3&gt; swigexample.fputs("Hello world",f); octave:3&gt; swigexample.fputs("Hello world", f);
octave:4&gt; swigexample.fclose(f); octave:4&gt; swigexample.fclose(f);
</pre></div> </pre></div>
@ -339,7 +339,7 @@ octave:4&gt; swigexample.fclose(f);
</p> </p>
<div class="targetlang"><pre>octave:1&gt; swigexample; <div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("junk","w"); octave:2&gt; f=swigexample.fopen("junk", "w");
octave:3&gt; f octave:3&gt; f
f = f =
@ -352,7 +352,7 @@ f =
</p> </p>
<div class="targetlang"><pre>octave:1&gt; swigexample; <div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("not there","r"); octave:2&gt; f=swigexample.fopen("not there", "r");
error: value on right hand side of assignment is undefined error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 2, column 2 </pre></div> error: evaluating assignment expression near line 2, column 2 </pre></div>
@ -365,7 +365,7 @@ For each wrapped structure and class, a <tt>swig_ref</tt> will be exposed that h
</p> </p>
<div class="code"><pre>struct Point{ <div class="code"><pre>struct Point{
int x,y; int x, y;
}; };
</pre></div> </pre></div>
@ -395,12 +395,12 @@ Methods also work as expected. For example, code wrapped in the following way
<div class="code"><pre>class Point{ <div class="code"><pre>class Point{
public: public:
int x,y; int x, y;
Point(int _x,int _y) : x(_x),y(_y) {} Point(int _x, int _y) : x(_x), y(_y) {}
double distance(const Point&amp; rhs) { double distance(const Point&amp; rhs) {
return sqrt(pow(x-rhs.x,2)+pow(y-rhs.y,2)); return sqrt(pow(x-rhs.x, 2)+pow(y-rhs.y, 2));
} }
void set(int _x,int _y) { void set(int _x, int _y) {
x=_x; y=_y; x=_x; y=_y;
} }
}; };
@ -410,8 +410,8 @@ can be used from Octave like this
</p> </p>
<div class="targetlang"> <div class="targetlang">
<pre>octave:1&gt; swigexample; <pre>octave:1&gt; swigexample;
octave:2&gt; p1=swigexample.Point(3,5); octave:2&gt; p1=swigexample.Point(3, 5);
octave:3&gt; p2=swigexample.Point(1,2); octave:3&gt; p2=swigexample.Point(1, 2);
octave:4&gt; p1.distance(p2) octave:4&gt; p1.distance(p2)
ans = 3.6056 ans = 3.6056
</pre></div> </pre></div>
@ -433,7 +433,7 @@ This differs from the usual pass-by-value (copy-on-write) semantics that Octave
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
octave:7> a=struct('x',4) octave:7> a=struct('x', 4)
a = a =
{ {
x = 4 x = 4
@ -464,7 +464,7 @@ However, when dealing with wrapped objects, one gets the behavior
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
octave:2> a=Point(3,5) octave:2> a=Point(3, 5)
a = a =
{ {
@ -478,7 +478,7 @@ b =
Point, ptr = 0x9afbbb0 Point, ptr = 0x9afbbb0
} }
octave:4> b.set(2,1); octave:4> b.set(2, 1);
octave:5> b.x, b.y octave:5> b.x, b.y
ans = 2 ans = 2
ans = 1 ans = 1
@ -621,7 +621,7 @@ Octave can also utilise friend (i.e. non-member) operators with a simple %rename
The %extend directive works the same as in other modules. The %extend directive works the same as in other modules.
</p> </p>
<p> <p>
You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the <tt>octave_value::{is_string,string_value,print}</tt> functions are routed to a special method <tt>__str__</tt> that can be defined inside an %extend. You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the <tt>octave_value::{is_string, string_value, print}</tt> functions are routed to a special method <tt>__str__</tt> that can be defined inside an %extend.
</p> </p>
<div class="code"><pre> <div class="code"><pre>
%extend A { %extend A {
@ -639,7 +639,7 @@ Then in Octave one gets,
octave:1&gt; a=A(4); octave:1&gt; a=A(4);
octave:2&gt; a octave:2&gt; a
a = 4 a = 4
octave:3&gt; printf("%s\n",a); octave:3&gt; printf("%s\n", a);
4 4
octave:4&gt; a.__str__() octave:4&gt; a.__str__()
4 4
@ -664,7 +664,7 @@ For example, function templates can be instantiated as follows:
<div class="code"><pre>%module swigexample <div class="code"><pre>%module swigexample
%inline { %inline {
template&lt;class __scalar&gt; template&lt;class __scalar&gt;
__scalar mul(__scalar a,__scalar b) { __scalar mul(__scalar a, __scalar b) {
return a*b; return a*b;
} }
} }
@ -677,11 +677,11 @@ and then used from Octave
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1> mul(4,3) octave:1> mul(4, 3)
ans = 12 ans = 12
octave:2> mul(4.2,3.6) octave:2> mul(4.2, 3.6)
ans = 15.120 ans = 15.120
octave:3> mul(3+4i,10+2i) octave:3> mul(3+4i, 10+2i)
ans = 22 + 46i ans = 22 + 46i
</pre></div> </pre></div>
@ -722,11 +722,11 @@ octave:2> a=sum_complex(2+3i);
octave:3> a.add(2) octave:3> a.add(2)
ans = ans =
(4,3) (4, 3)
octave:4> a.add(3+i) octave:4> a.add(3+i)
ans = ans =
(7,4) (7, 4)
</pre></div> </pre></div>
@ -766,7 +766,7 @@ For example,
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; a=subclass(); octave:1&gt; a=subclass();
octave:2&gt; a.my_var = 4; octave:2&gt; a.my_var = 4;
octave:3&gt; a.my_method = @(self) printf("my_var = ",self.my_var); octave:3&gt; a.my_method = @(self) printf("my_var = ", self.my_var);
octave:4&gt; a.my_method(); octave:4&gt; a.my_method();
my_var = 4 my_var = 4
</pre></div> </pre></div>
@ -790,7 +790,7 @@ void call_your_method(A&amp; a) {
Then from Octave you can say: Then from Octave you can say:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(),@my_method); octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self) octave:2&gt; function my_method(self)
octave:3&gt; printf("octave-side routine called\n"); octave:3&gt; printf("octave-side routine called\n");
octave:4&gt; end octave:4&gt; end
@ -801,7 +801,7 @@ octave-side routine called
or more concisely, or more concisely,
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(),'my_method',@(self) printf("octave-side routine called\n")); octave:1&gt; B=@() subclass(A(), 'my_method', @(self) printf("octave-side routine called\n"));
octave:2&gt; call_your_method(B()); octave:2&gt; call_your_method(B());
octave-side routine called octave-side routine called
</pre></div> </pre></div>
@ -809,10 +809,10 @@ octave-side routine called
Note that you have to enable directors via the %feature directive (see other modules for this). Note that you have to enable directors via the %feature directive (see other modules for this).
</p> </p>
<p> <p>
<tt>subclass()</tt> will accept any number of C++ bases or other <tt>subclass()</tt>'ed objects, <tt>(string,octave_value)</tt> pairs, and <tt>function_handles</tt>. In the first case, these are taken as base classes; in the second case, as named members (either variables or functions, depending on whether the given value is a function handle); in the third case, as member functions whose name is taken from the given function handle. E.g., <tt>subclass()</tt> will accept any number of C++ bases or other <tt>subclass()</tt>'ed objects, <tt>(string, octave_value)</tt> pairs, and <tt>function_handles</tt>. In the first case, these are taken as base classes; in the second case, as named members (either variables or functions, depending on whether the given value is a function handle); in the third case, as member functions whose name is taken from the given function handle. E.g.,
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func', octave:1&gt; B=@(some_var=2) subclass(A(), 'some_var', some_var, @some_func, 'another_func',
@(self) do_stuff()) @(self) do_stuff())
</pre></div> </pre></div>
<p> <p>
@ -822,7 +822,7 @@ You can also assign non-C++ member variables and functions after construct time.
There is limited support for explicitly referencing C++ bases. So, in the example above, we could have There is limited support for explicitly referencing C++ bases. So, in the example above, we could have
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(),@my_method); octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self) octave:2&gt; function my_method(self)
octave:3&gt; self.A.my_method(); octave:3&gt; self.A.my_method();
octave:4&gt; printf("octave-side routine called\n"); octave:4&gt; printf("octave-side routine called\n");
@ -887,7 +887,7 @@ Various STL library files are provided for wrapping STL containers.
Octave provides a rich set of classes for dealing with matrices. Currently there are no built-in typemaps to deal with those. However, these are relatively straight forward for users to add themselves (see the docs on typemaps). Without much work (a single typemap decl-- say, 5 lines of code in the interface file), it would be possible to have a function Octave provides a rich set of classes for dealing with matrices. Currently there are no built-in typemaps to deal with those. However, these are relatively straight forward for users to add themselves (see the docs on typemaps). Without much work (a single typemap decl-- say, 5 lines of code in the interface file), it would be possible to have a function
</p> </p>
<div class="code"><pre> <div class="code"><pre>
double my_det(const double* mat,int m,int n); double my_det(const double* mat, int m, int n);
</pre></div> </pre></div>
<p> <p>
that is accessed from Octave as, that is accessed from Octave as,

View file

@ -322,7 +322,7 @@ all goes well, you will be able to do this:
<div class="targetlang"><pre> <div class="targetlang"><pre>
$ perl $ perl
use example; use example;
print example::fact(4),"\n"; print example::fact(4), "\n";
24 24
</pre></div> </pre></div>
@ -770,7 +770,7 @@ is accessed as follows:</p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
use example; use example;
print $example::Spam,"\n"; print $example::Spam, "\n";
$example::Spam = $example::Spam + 4 $example::Spam = $example::Spam + 4
# ... etc ... # ... etc ...
@ -841,7 +841,7 @@ In Perl:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
use example; use example;
print $example::FOO,"\n"; # OK print $example::FOO, "\n"; # OK
$example::FOO = 2; # Error $example::FOO = 2; # Error
</pre> </pre>
</div> </div>
@ -855,7 +855,7 @@ usually gives a more natural Perl interface, for example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
use example; use example;
print example::FOO,"\n"; print example::FOO, "\n";
</pre> </pre>
</div> </div>
@ -978,7 +978,7 @@ accessor functions as described in the "SWIG Basics" chapter. For example,
<div class="code"><pre> <div class="code"><pre>
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -1004,8 +1004,8 @@ These functions are then used to access structure data from Perl as follows:
<div class="targetlang"><pre> <div class="targetlang"><pre>
$v = example::new_Vector(); $v = example::new_Vector();
print example::Vector_x_get($v),"\n"; # Get x component print example::Vector_x_get($v), "\n"; # Get x component
example::Vector_x_set($v,7.8); # Change x component example::Vector_x_set($v, 7.8); # Change x component
</pre></div> </pre></div>
<p> <p>
@ -1148,14 +1148,14 @@ In Perl, these functions are used in a straightforward manner:
<div class="targetlang"><pre> <div class="targetlang"><pre>
use example; use example;
$l = example::new_List(); $l = example::new_List();
example::List_insert($l,"Ale"); example::List_insert($l, "Ale");
example::List_insert($l,"Stout"); example::List_insert($l, "Stout");
example::List_insert($l,"Lager") example::List_insert($l, "Lager")
example::List_print($l) example::List_print($l)
Lager Lager
Stout Stout
Ale Ale
print example::List_length_get($l),"\n"; print example::List_length_get($l), "\n";
3 3
</pre></div> </pre></div>
@ -1238,8 +1238,8 @@ Now, in Perl, the methods are accessed as follows:
use example; use example;
example::foo_i(3); example::foo_i(3);
$s = example::new_Spam(); $s = example::new_Spam();
example::Spam_foo_i($s,3); example::Spam_foo_i($s, 3);
example::Spam_foo_d($s,3.14); example::Spam_foo_d($s, 3.14);
</pre> </pre>
</div> </div>
@ -1286,7 +1286,7 @@ a single Perl module. The name of the module is determined by the
<div class="targetlang"><pre> <div class="targetlang"><pre>
$ perl5 $ perl5
use example; # load the example module use example; # load the example module
print example::fact(4),"\n" # Call a function in it print example::fact(4), "\n" # Call a function in it
24 24
</pre></div> </pre></div>
@ -1365,7 +1365,7 @@ all of the functions in that module will be installed into the package
<div class="targetlang"><pre> <div class="targetlang"><pre>
use example; # Load the module like before use example; # Load the module like before
print Foo::fact(4),"\n"; # Call a function in package FooBar print Foo::fact(4), "\n"; # Call a function in package FooBar
</pre></div> </pre></div>
--> -->
@ -1417,10 +1417,10 @@ In Perl, this allows you to pass simple values. For example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
$a = example::add(3,4); $a = example::add(3, 4);
print "$a\n"; print "$a\n";
7 7
$b = example::sub(7,4); $b = example::sub(7, 4);
print "$b\n"; print "$b\n";
3 3
</pre> </pre>
@ -1552,7 +1552,7 @@ Now, in Perl:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
($r,$c) = example::get_dimensions($m); ($r, $c) = example::get_dimensions($m);
</pre> </pre>
</div> </div>
@ -1578,7 +1578,7 @@ In Perl:
<pre> <pre>
use example; use example;
$c = 0.0; $c = 0.0;
example::add(3,4,\$c); example::add(3, 4, \$c);
print "$c\n"; print "$c\n";
7 7
</pre> </pre>
@ -1830,7 +1830,7 @@ the typemap system follows <tt>typedef</tt> declarations. For example:
<pre> <pre>
%typemap(in) int n { %typemap(in) int n {
$1 = (int) SvIV($input); $1 = (int) SvIV($input);
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
%inline %{ %inline %{
typedef int Integer; typedef int Integer;
@ -1852,7 +1852,7 @@ Typemaps can also be defined for groups of consecutive arguments. For example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
%typemap(in) (char *str, unsigned len) { %typemap(in) (char *str, unsigned len) {
$1 = SvPV($input,$2); $1 = SvPV($input, $2);
}; };
int count(char c, char *str, unsigned len); int count(char c, char *str, unsigned len);
@ -1867,7 +1867,7 @@ parameter is omitted):
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
example::count("e","Hello World"); example::count("e", "Hello World");
1 1
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
@ -2156,7 +2156,7 @@ reference to be used as a char ** datatype.
$1 = (char **) malloc((len+2)*sizeof(char *)); $1 = (char **) malloc((len+2)*sizeof(char *));
for (i = 0; i &lt;= len; i++) { for (i = 0; i &lt;= len; i++) {
tv = av_fetch(tempav, i, 0); tv = av_fetch(tempav, i, 0);
$1[i] = (char *) SvPV(*tv,PL_na); $1[i] = (char *) SvPV(*tv, PL_na);
} }
$1[i] = NULL; $1[i] = NULL;
}; };
@ -2170,16 +2170,16 @@ reference to be used as a char ** datatype.
%typemap(out) char ** { %typemap(out) char ** {
AV *myav; AV *myav;
SV **svs; SV **svs;
int i = 0,len = 0; int i = 0, len = 0;
/* Figure out how many elements we have */ /* Figure out how many elements we have */
while ($1[len]) while ($1[len])
len++; len++;
svs = (SV **) malloc(len*sizeof(SV *)); svs = (SV **) malloc(len*sizeof(SV *));
for (i = 0; i &lt; len ; i++) { for (i = 0; i &lt; len ; i++) {
svs[i] = sv_newmortal(); svs[i] = sv_newmortal();
sv_setpv((SV*)svs[i],$1[i]); sv_setpv((SV*)svs[i], $1[i]);
}; };
myav = av_make(len,svs); myav = av_make(len, svs);
free(svs); free(svs);
$result = newRV_noinc((SV*)myav); $result = newRV_noinc((SV*)myav);
sv_2mortal($result); sv_2mortal($result);
@ -2191,7 +2191,7 @@ reference to be used as a char ** datatype.
int print_args(char **argv) { int print_args(char **argv) {
int i = 0; int i = 0;
while (argv[i]) { while (argv[i]) {
printf("argv[%d] = %s\n", i,argv[i]); printf("argv[%d] = %s\n", i, argv[i]);
i++; i++;
} }
return i; return i;
@ -2216,7 +2216,7 @@ use argv;
@a = ("Dave", "Mike", "John", "Mary"); # Create an array of strings @a = ("Dave", "Mike", "John", "Mary"); # Create an array of strings
argv::print_args(\@a); # Pass it to our C function argv::print_args(\@a); # Pass it to our C function
$b = argv::get_args(); # Get array of strings from C $b = argv::get_args(); # Get array of strings from C
print @$b,"\n"; # Print it out print @$b, "\n"; # Print it out
</pre></div> </pre></div>
@ -2241,10 +2241,10 @@ can be done using the <tt>EXTEND()</tt> macro as in:
<div class="code"><pre> <div class="code"><pre>
%typemap(argout) int *OUTPUT { %typemap(argout) int *OUTPUT {
if (argvi &gt;= items) { if (argvi &gt;= items) {
EXTEND(sp,1); /* Extend the stack by 1 object */ EXTEND(sp, 1); /* Extend the stack by 1 object */
} }
$result = sv_newmortal(); $result = sv_newmortal();
sv_setiv($target,(IV) *($1)); sv_setiv($target, (IV) *($1));
argvi++; argvi++;
} }
</pre></div> </pre></div>
@ -2271,7 +2271,7 @@ its arguments. This example describes the implementation of the <tt>OUTPUT</tt>
// We don't care what the input value is. Ignore, but set to a temporary variable // We don't care what the input value is. Ignore, but set to a temporary variable
%typemap(in,numinputs=0) double *OUTPUT(double junk) { %typemap(in, numinputs=0) double *OUTPUT(double junk) {
$1 = &amp;junk; $1 = &amp;junk;
} }
@ -2298,9 +2298,9 @@ For example:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
@r = multout(7,13); @r = multout(7, 13);
print "multout(7,13) = @r\n"; print "multout(7, 13) = @r\n";
($x,$y) = multout(7,13); ($x, $y) = multout(7, 13);
</pre></div> </pre></div>
<H3><a name="Perl5_nn36">33.8.4 Accessing array structure members</a></H3> <H3><a name="Perl5_nn36">33.8.4 Accessing array structure members</a></H3>
@ -2390,7 +2390,7 @@ A common misinterpretation of this function is the following Perl script:
$a = 3.5; $a = 3.5;
$b = 7.5; $b = 7.5;
$c = 0.0; # Output value $c = 0.0; # Output value
add($a,$b,\$c); # Place result in c (Except that it doesn't work) add($a, $b, \$c); # Place result in c (Except that it doesn't work)
</pre></div> </pre></div>
<p> <p>
@ -2426,7 +2426,7 @@ Now, if you place this before the add function, you can do this:
$a = 3.5; $a = 3.5;
$b = 7.5; $b = 7.5;
$c = 0.0; $c = 0.0;
add($a,$b,\$c); # Now it works! add($a, $b, \$c); # Now it works!
print "$c\n"; print "$c\n";
</pre></div> </pre></div>
@ -2566,7 +2566,7 @@ Suppose you have the following SWIG interface file:
struct Vector { struct Vector {
Vector(double x, double y, double z); Vector(double x, double y, double z);
~Vector(); ~Vector();
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -2608,7 +2608,7 @@ sub new () {
$OWNER{$self} = 1; $OWNER{$self} = 1;
my %retval; my %retval;
tie %retval, "example::Vector", $self; tie %retval, "example::Vector", $self;
return bless \%retval,"Vector"; return bless \%retval, "Vector";
} }
sub DESTROY { sub DESTROY {
@ -2622,25 +2622,25 @@ sub DESTROY {
} }
sub FETCH { sub FETCH {
my ($self,$field) = @_; my ($self, $field) = @_;
my $member_func = "vectorc::Vector_${field}_get"; my $member_func = "vectorc::Vector_${field}_get";
my $val = &amp;$member_func($self); my $val = &amp;$member_func($self);
if (exists $BLESSEDMEMBERS{$field}) { if (exists $BLESSEDMEMBERS{$field}) {
return undef if (!defined($val)); return undef if (!defined($val));
my %retval; my %retval;
tie %retval,$BLESSEDMEMBERS{$field},$val; tie %retval, $BLESSEDMEMBERS{$field}, $val;
return bless \%retval, $BLESSEDMEMBERS{$field}; return bless \%retval, $BLESSEDMEMBERS{$field};
} }
return $val; return $val;
} }
sub STORE { sub STORE {
my ($self,$field,$newval) = @_; my ($self, $field, $newval) = @_;
my $member_func = "vectorc::Vector_${field}_set"; my $member_func = "vectorc::Vector_${field}_set";
if (exists $BLESSEDMEMBERS{$field}) { if (exists $BLESSEDMEMBERS{$field}) {
&amp;$member_func($self,tied(%{$newval})); &amp;$member_func($self, tied(%{$newval}));
} else { } else {
&amp;$member_func($self,$newval); &amp;$member_func($self, $newval);
} }
} }
</pre></div> </pre></div>
@ -2662,8 +2662,8 @@ To use our new proxy class we can simply do the following:
<div class="targetlang"><pre> <div class="targetlang"><pre>
# Perl code using Vector class # Perl code using Vector class
$v = new Vector(2,3,4); $v = new Vector(2, 3, 4);
$w = Vector-&gt;new(-1,-2,-3); $w = Vector-&gt;new(-1, -2, -3);
# Assignment of a single member # Assignment of a single member
$v-&gt;{x} = 7.5; $v-&gt;{x} = 7.5;
@ -2706,7 +2706,7 @@ Vector object:
<div class="code"><pre> <div class="code"><pre>
Vector *new_Vector(double x, double y, double z) { Vector *new_Vector(double x, double y, double z) {
Vector *v; Vector *v;
v = new Vector(x,y,z); // Call C++ constructor v = new Vector(x, y, z); // Call C++ constructor
return v; return v;
} }
</pre></div> </pre></div>
@ -2747,7 +2747,7 @@ done using the <tt>DISOWN</tt> method.
<div class="targetlang"><pre> <div class="targetlang"><pre>
# Perl code to change ownership of an object # Perl code to change ownership of an object
$v = new Vector(x,y,z); $v = new Vector(x, y, z);
$v-&gt;DISOWN(); $v-&gt;DISOWN();
</pre></div> </pre></div>
@ -3002,10 +3002,10 @@ low-level helper functions. For example, this code now seems to work:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
my $a = my $a =
[[1,0,0,0], [[1, 0, 0, 0],
[0,1,0,0], [0, 1, 0, 0],
[0,0,1,0], [0, 0, 1, 0],
[0,0,0,1]]; [0, 0, 0, 1]];
set_transform($im, $a); set_transform($im, $a);
</pre> </pre>
</div> </div>

View file

@ -295,7 +295,7 @@ the use of automatically generated accessor functions.
%inline %{ %inline %{
double seki = 2; double seki = 2;
void print_seki() { void print_seki() {
zend_printf("seki is now %f\n",seki); zend_printf("seki is now %f\n", seki);
} }
%} %}
</pre></div> </pre></div>
@ -463,7 +463,7 @@ One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
<div class="code"><pre> <div class="code"><pre>
%module example %module example
%include "cpointer.i" %include "cpointer.i"
%pointer_functions(int,intp) %pointer_functions(int, intp)
void add( int *in1, int *in2, int *result); void add( int *in1, int *in2, int *result);
</pre></div> </pre></div>
@ -513,7 +513,7 @@ include("example.php");
$in1 = 3; $in1 = 3;
$in2 = 5; $in2 = 5;
$result= add($in1,$in2); # Note using variables for the input is unnecessary. $result= add($in1, $in2); # Note using variables for the input is unnecessary.
echo "The sum $in1 + $in2 = $result\n"; echo "The sum $in1 + $in2 = $result\n";
?&gt; ?&gt;
@ -559,7 +559,7 @@ include("example.php");
$in1 = 3; $in1 = 3;
$in2 = 5; $in2 = 5;
$result = 0; $result = 0;
add($in1,$in2,$result); add($in1, $in2, $result);
echo "The sum $in1 + $in2 = $result\n"; echo "The sum $in1 + $in2 = $result\n";
?&gt; ?&gt;
@ -603,7 +603,7 @@ This interface file
class Vector { class Vector {
public: public:
double x,y,z; double x, y, z;
Vector(); Vector();
~Vector(); ~Vector();
double magnitude(); double magnitude();
@ -627,7 +627,7 @@ Would be used in the following way from PHP:
$v-&gt;y = 4; $v-&gt;y = 4;
$v-&gt;z = 5; $v-&gt;z = 5;
echo "Magnitude of ($v-&gt;x,$v-&gt;y,$v-&gt;z) = " . $v-&gt;magnitude() . "\n"; echo "Magnitude of ($v-&gt;x, $v-&gt;y, $v-&gt;z) = " . $v-&gt;magnitude() . "\n";
$v = NULL; # destructor called. $v = NULL; # destructor called.
@ -656,17 +656,17 @@ in the following PHP functions:
<div class="code"><pre> <div class="code"><pre>
new_Vector(); new_Vector();
Vector_x_set($obj,$d); Vector_x_set($obj, $d);
Vector_x_get($obj); Vector_x_get($obj);
Vector_y_set($obj,$d); Vector_y_set($obj, $d);
Vector_y_get($obj); Vector_y_get($obj);
Vector_z_set($obj,$d); Vector_z_set($obj, $d);
Vector_z_get($obj); Vector_z_get($obj);
Vector_magnitude($obj); Vector_magnitude($obj);
new_Complex(); new_Complex();
Complex_re_set($obj,$d); Complex_re_set($obj, $d);
Complex_re_get($obj); Complex_re_get($obj);
Complex_im_set($obj,$d); Complex_im_set($obj, $d);
Complex_im_get($obj); Complex_im_get($obj);
</pre></div> </pre></div>

View file

@ -224,7 +224,7 @@ For example:
<div class="code"> <div class="code">
<pre> <pre>
%define ARRAYHELPER(type,name) %define ARRAYHELPER(type, name)
%inline %{ %inline %{
type *new_ ## name (int nitems) { type *new_ ## name (int nitems) {
return (type *) malloc(sizeof(type)*nitems); return (type *) malloc(sizeof(type)*nitems);
@ -269,7 +269,7 @@ SWIG-1.3.12 and newer releases support variadic preprocessor macros. For exampl
<div class="code"> <div class="code">
<pre> <pre>
#define DEBUGF(fmt,...) fprintf(stderr,fmt,__VA_ARGS__) #define DEBUGF(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
</pre> </pre>
</div> </div>
@ -281,12 +281,12 @@ macros defined using <tt>%define</tt>.
<p> <p>
SWIG allows a variable number of arguments to be empty. However, this often results SWIG allows a variable number of arguments to be empty. However, this often results
in an extra comma (,) and syntax error in the resulting expansion. For example: in an extra comma (, ) and syntax error in the resulting expansion. For example:
</p> </p>
<div class="code"> <div class="code">
<pre> <pre>
DEBUGF("hello"); --&gt; fprintf(stderr,"hello",); DEBUGF("hello"); --&gt; fprintf(stderr, "hello", );
</pre> </pre>
</div> </div>
@ -296,7 +296,7 @@ To get rid of the extra comma, use <tt>##</tt> like this:
<div class="code"> <div class="code">
<pre> <pre>
#define DEBUGF(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__) #define DEBUGF(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__)
</pre> </pre>
</div> </div>
@ -306,7 +306,7 @@ SWIG also supports GNU-style variadic macros. For example:
<div class="code"> <div class="code">
<pre> <pre>
#define DEBUGF(fmt, args...) fprintf(stdout,fmt,args) #define DEBUGF(fmt, args...) fprintf(stdout, fmt, args)
</pre> </pre>
</div> </div>
@ -425,7 +425,7 @@ whereas
<div class="code"> <div class="code">
<pre> <pre>
#define SWIG_macro(CAST) (CAST)$input #define SWIG_macro(CAST) (CAST)$input
%typemap(in,noblock=1) Int {$1= SWIG_macro(int);} %typemap(in, noblock=1) Int {$1= SWIG_macro(int);}
</pre> </pre>
</div> </div>

View file

@ -1294,7 +1294,7 @@ a very natural interface. For example,
<div class="code"><pre> <div class="code"><pre>
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -1589,11 +1589,11 @@ structure. All of the usual Python utility functions work normally:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; b = Bar() &gt;&gt;&gt; b = Bar()
&gt;&gt;&gt; instance(b,Foo) &gt;&gt;&gt; instance(b, Foo)
1 1
&gt;&gt;&gt; issubclass(Bar,Foo) &gt;&gt;&gt; issubclass(Bar, Foo)
1 1
&gt;&gt;&gt; issubclass(Foo,Bar) &gt;&gt;&gt; issubclass(Foo, Bar)
0 0
</pre> </pre>
</div> </div>
@ -1836,8 +1836,8 @@ When wrapped, it works like you expect:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; c = Complex(3,4) &gt;&gt;&gt; c = Complex(3, 4)
&gt;&gt;&gt; d = Complex(7,8) &gt;&gt;&gt; d = Complex(7, 8)
&gt;&gt;&gt; e = c + d &gt;&gt;&gt; e = c + d
&gt;&gt;&gt; e.re() &gt;&gt;&gt; e.re()
10.0 10.0
@ -1905,7 +1905,7 @@ submodules or packages. For example, if you have a file like this,
namespace foo { namespace foo {
int fact(int n); int fact(int n);
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
}; };
</pre> </pre>
@ -1984,7 +1984,7 @@ struct pair {
~pair(); ~pair();
}; };
%template(pairii) pair&lt;int,int&gt;; %template(pairii) pair&lt;int, int&gt;;
</pre> </pre>
</div> </div>
@ -1995,7 +1995,7 @@ In Python:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; import example &gt;&gt;&gt; import example
&gt;&gt;&gt; p = example.pairii(3,4) &gt;&gt;&gt; p = example.pairii(3, 4)
&gt;&gt;&gt; p.first &gt;&gt;&gt; p.first
3 3
&gt;&gt;&gt; p.second &gt;&gt;&gt; p.second
@ -2203,8 +2203,8 @@ class Foo(object):
def __del__(self): def __del__(self):
if self.thisown: if self.thisown:
_example.delete_Foo(self.this) _example.delete_Foo(self.this)
def spam(self,arg1): def spam(self, arg1):
return _example.Foo_spam(self.this,arg1) return _example.Foo_spam(self.this, arg1)
x = property(_example.Foo_x_get, _example.Foo_x_set) x = property(_example.Foo_x_get, _example.Foo_x_set)
</pre> </pre>
</div> </div>
@ -3296,11 +3296,11 @@ For example, you might get errors like this:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = [ &gt;&gt;&gt; a = [
... [1,0,0,0], ... [1, 0, 0, 0],
... [0,1,0,0], ... [0, 1, 0, 0],
... [0,0,1,0], ... [0, 0, 1, 0],
... [0,0,0,1]] ... [0, 0, 0, 1]]
&gt;&gt;&gt; set_transform(im,a) &gt;&gt;&gt; set_transform(im, a)
Traceback (most recent call last): Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ? File "&lt;stdin&gt;", line 1, in ?
TypeError: Type error. Expected _p_a_4__double TypeError: Type error. Expected _p_a_4__double
@ -3340,11 +3340,11 @@ From Python, you could then write code like this:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = new_mat44() &gt;&gt;&gt; a = new_mat44()
&gt;&gt;&gt; mat44_set(a,0,0,1.0) &gt;&gt;&gt; mat44_set(a, 0, 0, 1.0)
&gt;&gt;&gt; mat44_set(a,1,1,1.0) &gt;&gt;&gt; mat44_set(a, 1, 1, 1.0)
&gt;&gt;&gt; mat44_set(a,2,2,1.0) &gt;&gt;&gt; mat44_set(a, 2, 2, 1.0)
... ...
&gt;&gt;&gt; set_transform(im,a) &gt;&gt;&gt; set_transform(im, a)
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
</div> </div>
@ -3372,12 +3372,12 @@ void set_transform(Image *im, double x[4][4]);
... ...
/* Rewrite the high level interface to set_transform */ /* Rewrite the high level interface to set_transform */
%pythoncode %{ %pythoncode %{
def set_transform(im,x): def set_transform(im, x):
a = new_mat44() a = new_mat44()
for i in range(4): for i in range(4):
for j in range(4): for j in range(4):
mat44_set(a,i,j,x[i][j]) mat44_set(a, i, j, x[i][j])
_example.set_transform(im,a) _example.set_transform(im, a)
free_mat44(a) free_mat44(a)
%} %}
</pre> </pre>
@ -3391,11 +3391,11 @@ low-level helper functions. For example, this code now seems to work:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = [ &gt;&gt;&gt; a = [
... [1,0,0,0], ... [1, 0, 0, 0],
... [0,1,0,0], ... [0, 1, 0, 0],
... [0,0,1,0], ... [0, 0, 1, 0],
... [0,0,0,1]] ... [0, 0, 0, 1]]
&gt;&gt;&gt; set_transform(im,a) &gt;&gt;&gt; set_transform(im, a)
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
</div> </div>
@ -3624,13 +3624,13 @@ Here is a simple example:
%} %}
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
%extend Vector { %extend Vector {
char *__str__() { char *__str__() {
static char tmp[1024]; static char tmp[1024];
sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z); sprintf(tmp, "Vector(%g, %g, %g)", $self-&gt;x, $self-&gt;y, $self-&gt;z);
return tmp; return tmp;
} }
Vector(double x, double y, double z) { Vector(double x, double y, double z) {
@ -3650,9 +3650,9 @@ Now, in Python
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; v = example.Vector(2,3,4) &gt;&gt;&gt; v = example.Vector(2, 3, 4)
&gt;&gt;&gt; print v &gt;&gt;&gt; print v
Vector(2,3,4) Vector(2, 3, 4)
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
</div> </div>
@ -3683,10 +3683,10 @@ Use it like this:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; import example &gt;&gt;&gt; import example
&gt;&gt;&gt; v = example.Vector(2,3,4) &gt;&gt;&gt; v = example.Vector(2, 3, 4)
&gt;&gt;&gt; w = example.Vector(10,11,12) &gt;&gt;&gt; w = example.Vector(10, 11, 12)
&gt;&gt;&gt; print v+w &gt;&gt;&gt; print v+w
Vector(12,14,16) Vector(12, 14, 16)
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
</div> </div>
@ -3715,7 +3715,7 @@ or a NULL pointer perhaps). Here is a simple example of how you might handle th
%exception malloc { %exception malloc {
$action $action
if (!result) { if (!result) {
PyErr_SetString(PyExc_MemoryError,"Not enough memory"); PyErr_SetString(PyExc_MemoryError, "Not enough memory");
SWIG_fail; SWIG_fail;
} }
} }
@ -3888,10 +3888,10 @@ In Python, this allows you to pass simple values. For example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = add(3,4) &gt;&gt;&gt; a = add(3, 4)
&gt;&gt;&gt; print a &gt;&gt;&gt; print a
7 7
&gt;&gt;&gt; b = sub(7,4) &gt;&gt;&gt; b = sub(7, 4)
&gt;&gt;&gt; print b &gt;&gt;&gt; print b
3 3
&gt;&gt;&gt; &gt;&gt;&gt;
@ -4034,7 +4034,7 @@ Now, in Python:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; r,c = get_dimensions(m) &gt;&gt;&gt; r, c = get_dimensions(m)
</pre> </pre>
</div> </div>
@ -4075,7 +4075,7 @@ extern void add(int x, int y, int *result);
</div> </div>
<p> <p>
The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create, The <tt>%pointer_functions(type, name)</tt> macro generates five helper functions that can be used to create,
destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows: destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows:
</p> </p>
@ -4098,7 +4098,7 @@ In Python, you would use the functions like this:
&gt;&gt;&gt; result = new_intp() &gt;&gt;&gt; result = new_intp()
&gt;&gt;&gt; print result &gt;&gt;&gt; print result
_108fea8_p_int _108fea8_p_int
&gt;&gt;&gt; add(3,4,result) &gt;&gt;&gt; add(3, 4, result)
&gt;&gt;&gt; print intp_value(result) &gt;&gt;&gt; print intp_value(result)
7 7
&gt;&gt;&gt; &gt;&gt;&gt;
@ -4106,13 +4106,13 @@ _108fea8_p_int
</div> </div>
<p> <p>
If you replace <tt>%pointer_functions()</tt> by <tt>%pointer_class(type,name)</tt>, the interface is more class-like. If you replace <tt>%pointer_functions()</tt> by <tt>%pointer_class(type, name)</tt>, the interface is more class-like.
</p> </p>
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; result = intp() &gt;&gt;&gt; result = intp()
&gt;&gt;&gt; add(3,4,result) &gt;&gt;&gt; add(3, 4, result)
&gt;&gt;&gt; print result.value() &gt;&gt;&gt; print result.value()
7 7
</pre> </pre>
@ -4164,7 +4164,7 @@ For instance, you will be able to do this in Python:
&gt;&gt;&gt; a = intArray(10000000) # Array of 10-million integers &gt;&gt;&gt; a = intArray(10000000) # Array of 10-million integers
&gt;&gt;&gt; for i in xrange(10000): # Set some values &gt;&gt;&gt; for i in xrange(10000): # Set some values
... a[i] = i ... a[i] = i
&gt;&gt;&gt; sumitems(a,10000) &gt;&gt;&gt; sumitems(a, 10000)
49995000 49995000
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
@ -4384,7 +4384,7 @@ you might define a typemap like this:
%typemap(in) int { %typemap(in) int {
$1 = (int) PyLong_AsLong($input); $1 = (int) PyLong_AsLong($input);
printf("Received an integer : %d\n",$1); printf("Received an integer : %d\n", $1);
} }
%inline %{ %inline %{
extern int fact(int n); extern int fact(int n);
@ -4423,7 +4423,7 @@ You can refine this by supplying an optional parameter name. For example:
%typemap(in) int nonnegative { %typemap(in) int nonnegative {
$1 = (int) PyLong_AsLong($input); $1 = (int) PyLong_AsLong($input);
if ($1 &lt; 0) { if ($1 &lt; 0) {
PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); PyErr_SetString(PyExc_ValueError, "Expected a nonnegative value.");
SWIG_fail; SWIG_fail;
} }
} }
@ -4448,7 +4448,7 @@ the typemap system follows <tt>typedef</tt> declarations. For example:
<pre> <pre>
%typemap(in) int n { %typemap(in) int n {
$1 = (int) PyLong_AsLong($input); $1 = (int) PyLong_AsLong($input);
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
%inline %{ %inline %{
typedef int Integer; typedef int Integer;
@ -4480,7 +4480,7 @@ parameter is omitted):
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; example.count('e','Hello World') &gt;&gt;&gt; example.count('e', 'Hello World')
1 1
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
@ -4756,18 +4756,18 @@ object to be used as a <tt>char **</tt> object.
int i = 0; int i = 0;
$1 = (char **) malloc((size+1)*sizeof(char *)); $1 = (char **) malloc((size+1)*sizeof(char *));
for (i = 0; i &lt; size; i++) { for (i = 0; i &lt; size; i++) {
PyObject *o = PyList_GetItem($input,i); PyObject *o = PyList_GetItem($input, i);
if (PyString_Check(o)) { if (PyString_Check(o)) {
$1[i] = PyString_AsString(PyList_GetItem($input,i)); $1[i] = PyString_AsString(PyList_GetItem($input, i));
} else { } else {
free($1); free($1);
PyErr_SetString(PyExc_TypeError,"list must contain strings"); PyErr_SetString(PyExc_TypeError, "list must contain strings");
SWIG_fail; SWIG_fail;
} }
} }
$1[i] = 0; $1[i] = 0;
} else { } else {
PyErr_SetString(PyExc_TypeError,"not a list"); PyErr_SetString(PyExc_TypeError, "not a list");
SWIG_fail; SWIG_fail;
} }
} }
@ -4782,7 +4782,7 @@ object to be used as a <tt>char **</tt> object.
int print_args(char **argv) { int print_args(char **argv) {
int i = 0; int i = 0;
while (argv[i]) { while (argv[i]) {
printf("argv[%d] = %s\n", i,argv[i]); printf("argv[%d] = %s\n", i, argv[i]);
i++; i++;
} }
return i; return i;
@ -4855,18 +4855,18 @@ previous example:
$1 = PyList_Size($input); $1 = PyList_Size($input);
$2 = (char **) malloc(($1+1)*sizeof(char *)); $2 = (char **) malloc(($1+1)*sizeof(char *));
for (i = 0; i &lt; $1; i++) { for (i = 0; i &lt; $1; i++) {
PyObject *o = PyList_GetItem($input,i); PyObject *o = PyList_GetItem($input, i);
if (PyString_Check(o)) { if (PyString_Check(o)) {
$2[i] = PyString_AsString(PyList_GetItem($input,i)); $2[i] = PyString_AsString(PyList_GetItem($input, i));
} else { } else {
free($2); free($2);
PyErr_SetString(PyExc_TypeError,"list must contain strings"); PyErr_SetString(PyExc_TypeError, "list must contain strings");
SWIG_fail; SWIG_fail;
} }
} }
$2[i] = 0; $2[i] = 0;
} else { } else {
PyErr_SetString(PyExc_TypeError,"not a list"); PyErr_SetString(PyExc_TypeError, "not a list");
SWIG_fail; SWIG_fail;
} }
} }
@ -4929,7 +4929,7 @@ Traceback (most recent call last):
example.foo(["foo", "bar", "spam", "1"]) example.foo(["foo", "bar", "spam", "1"])
NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'. NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'.
Possible C/C++ prototypes are: Possible C/C++ prototypes are:
foo(int,char **) foo(int, char **)
foo() foo()
</pre> </pre>
</div> </div>
@ -4972,12 +4972,12 @@ A typemap can be used to handle this case as follows :
if (!PyTuple_Check($result)) { if (!PyTuple_Check($result)) {
PyObject *o2 = $result; PyObject *o2 = $result;
$result = PyTuple_New(1); $result = PyTuple_New(1);
PyTuple_SetItem($result,0,o2); PyTuple_SetItem($result, 0, o2);
} }
o3 = PyTuple_New(1); o3 = PyTuple_New(1);
PyTuple_SetItem(o3,0,o); PyTuple_SetItem(o3, 0, o);
o2 = $result; o2 = $result;
$result = PySequence_Concat(o2,o3); $result = PySequence_Concat(o2, o3);
Py_DECREF(o2); Py_DECREF(o2);
Py_DECREF(o3); Py_DECREF(o3);
} }
@ -5001,7 +5001,7 @@ no meaningful input value), an additional typemap can be written. For example:
</p> </p>
<div class="code"><pre> <div class="code"><pre>
%typemap(in,numinputs=0) double *OutValue(double temp) { %typemap(in, numinputs=0) double *OutValue(double temp) {
$1 = &amp;temp; $1 = &amp;temp;
} }
@ -5015,10 +5015,10 @@ function can now be used as follows:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; a = spam(4,5) &gt;&gt;&gt; a = spam(4, 5)
&gt;&gt;&gt; print a &gt;&gt;&gt; print a
(0, 2.45, 5.0) (0, 2.45, 5.0)
&gt;&gt;&gt; x,y,z = spam(4,5) &gt;&gt;&gt; x, y, z = spam(4, 5)
&gt;&gt;&gt; &gt;&gt;&gt;
</pre></div> </pre></div>
@ -5043,13 +5043,13 @@ This too, can be handled used typemaps as follows :
%typemap(in) double[4](double temp[4]) { // temp[4] becomes a local variable %typemap(in) double[4](double temp[4]) { // temp[4] becomes a local variable
int i; int i;
if (PyTuple_Check($input)) { if (PyTuple_Check($input)) {
if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) { if (!PyArg_ParseTuple($input, "dddd", temp, temp+1, temp+2, temp+3)) {
PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements"); PyErr_SetString(PyExc_TypeError, "tuple must have 4 elements");
SWIG_fail; SWIG_fail;
} }
$1 = &amp;temp[0]; $1 = &amp;temp[0];
} else { } else {
PyErr_SetString(PyExc_TypeError,"expected a tuple."); PyErr_SetString(PyExc_TypeError, "expected a tuple.");
SWIG_fail; SWIG_fail;
} }
} }
@ -5062,7 +5062,7 @@ Python as follows :
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; set_direction((0.5,0.0,1.0,-0.25)) &gt;&gt;&gt; set_direction((0.5, 0.0, 1.0, -0.25))
</pre></div> </pre></div>
<p> <p>
@ -5084,18 +5084,18 @@ arrays of different sizes. To do this, you might write a typemap as follows:
%typemap(in) double[ANY](double temp[$1_dim0]) { %typemap(in) double[ANY](double temp[$1_dim0]) {
int i; int i;
if (!PySequence_Check($input)) { if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); PyErr_SetString(PyExc_TypeError, "Expecting a sequence");
SWIG_fail; SWIG_fail;
} }
if (PyObject_Length($input) != $1_dim0) { if (PyObject_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements"); PyErr_SetString(PyExc_ValueError, "Expecting a sequence with $1_dim0 elements");
SWIG_fail; SWIG_fail;
} }
for (i =0; i &lt; $1_dim0; i++) { for (i =0; i &lt; $1_dim0; i++) {
PyObject *o = PySequence_GetItem($input,i); PyObject *o = PySequence_GetItem($input, i);
if (!PyFloat_Check(o)) { if (!PyFloat_Check(o)) {
Py_XDECREF(o); Py_XDECREF(o);
PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); PyErr_SetString(PyExc_ValueError, "Expecting a sequence of floats");
SWIG_fail; SWIG_fail;
} }
temp[i] = PyFloat_AsDouble(o); temp[i] = PyFloat_AsDouble(o);
@ -5130,18 +5130,18 @@ to use a helper function instead. This will greatly reduce the amount of wrappe
static int convert_darray(PyObject *input, double *ptr, int size) { static int convert_darray(PyObject *input, double *ptr, int size) {
int i; int i;
if (!PySequence_Check(input)) { if (!PySequence_Check(input)) {
PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); PyErr_SetString(PyExc_TypeError, "Expecting a sequence");
return 0; return 0;
} }
if (PyObject_Length(input) != size) { if (PyObject_Length(input) != size) {
PyErr_SetString(PyExc_ValueError,"Sequence size mismatch"); PyErr_SetString(PyExc_ValueError, "Sequence size mismatch");
return 0; return 0;
} }
for (i =0; i &lt; size; i++) { for (i =0; i &lt; size; i++) {
PyObject *o = PySequence_GetItem(input,i); PyObject *o = PySequence_GetItem(input, i);
if (!PyFloat_Check(o)) { if (!PyFloat_Check(o)) {
Py_XDECREF(o); Py_XDECREF(o);
PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); PyErr_SetString(PyExc_ValueError, "Expecting a sequence of floats");
return 0; return 0;
} }
ptr[i] = PyFloat_AsDouble(o); ptr[i] = PyFloat_AsDouble(o);
@ -5152,7 +5152,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) {
%} %}
%typemap(in) double [ANY](double temp[$1_dim0]) { %typemap(in) double [ANY](double temp[$1_dim0]) {
if (!convert_darray($input,temp,$1_dim0)) { if (!convert_darray($input, temp, $1_dim0)) {
SWIG_fail; SWIG_fail;
} }
$1 = &amp;temp[0]; $1 = &amp;temp[0];

View file

@ -146,7 +146,7 @@ file makeRData.R which contains the following
<pre> <pre>
source('BigFile.R') source('BigFile.R')
save(list=ls(all=TRUE),file="BigFile.RData", compress=TRUE) save(list=ls(all=TRUE), file="BigFile.RData", compress=TRUE)
q(save="no") q(save="no")
</pre> </pre>

View file

@ -1014,7 +1014,7 @@ void foo(char *c);</pre>
irb(main):002:0&gt; <b>foo("Hello")</b> # foo(char *c)</pre> irb(main):002:0&gt; <b>foo("Hello")</b> # foo(char *c)</pre>
</div> </div>
<p>Similarly, if you have a class like this,</p> <p>Similarly, if you have a class like this, </p>
<div class="code"> <div class="code">
<pre>class Foo { <pre>class Foo {
@ -1141,7 +1141,7 @@ like this, </p>
namespace foo { namespace foo {
int fact(int n); int fact(int n);
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
};</pre> };</pre>
</div> </div>
@ -1210,7 +1210,7 @@ struct pair {
~pair(); ~pair();
}; };
%template(Pairii) pair&lt;int,int&gt;;</pre> %template(Pairii) pair&lt;int, int&gt;;</pre>
</div> </div>
<p>In Ruby:</p> <p>In Ruby:</p>
@ -1273,7 +1273,7 @@ v.each { |x| puts x }
3 3
4 4
v.delete_if { |x| x == 3 } v.delete_if { |x| x == 3 }
=&gt; [2,4]</pre> =&gt; [2, 4]</pre>
</div> </div>
<p>The SWIG Ruby module provides also the ability for all the STL <p>The SWIG Ruby module provides also the ability for all the STL
@ -1303,7 +1303,7 @@ include NativeVector
v = NativeVector.new v = NativeVector.new
v &lt;&lt; 1 v &lt;&lt; 1
v &lt;&lt; [1,2] v &lt;&lt; [1, 2]
v &lt;&lt; 'hello' v &lt;&lt; 'hello'
class A; end class A; end
@ -1311,7 +1311,7 @@ class A; end
v &lt;&lt; A.new v &lt;&lt; A.new
puts v puts v
=&gt; [1, [1,2], 'hello', #&lt;A:0x245325&gt;] =&gt; [1, [1, 2], 'hello', #&lt;A:0x245325&gt;]
</pre> </pre>
</div> </div>
@ -1368,15 +1368,15 @@ a &lt;&lt; 1
a &lt;&lt; 2 a &lt;&lt; 2
a &lt;&lt; 3 a &lt;&lt; 3
a a
<b>=&gt; [1,2,3]</b> <b>=&gt; [1, 2, 3]</b>
# Custom sorting behavior defined by a Ruby proc # Custom sorting behavior defined by a Ruby proc
b = IntSet.new( proc { |a,b| a &gt; b } ) b = IntSet.new( proc { |a, b| a &gt; b } )
b &lt;&lt; 1 b &lt;&lt; 1
b &lt;&lt; 2 b &lt;&lt; 2
b &lt;&lt; 3 b &lt;&lt; 3
b b
<b>=&gt; [3,2,1]</b> <b>=&gt; [3, 2, 1]</b>
</pre> </pre>
</div> </div>
@ -1493,7 +1493,7 @@ like this: </p>
}</pre> }</pre>
</div> </div>
<p>Then, if you have a class like this,</p> <p>Then, if you have a class like this, </p>
<div class="code"> <div class="code">
<pre>class Foo { <pre>class Foo {
@ -1665,7 +1665,7 @@ a comma-separated list of aliases to the <tt>%alias</tt>
directive, e.g. </p> directive, e.g. </p>
<div class="code"> <div class="code">
<pre>%alias MyArray::length "amount,quantity,size";</pre> <pre>%alias MyArray::length "amount, quantity, size";</pre>
</div> </div>
<p> From an end-user's standpoint, there's no functional <p> From an end-user's standpoint, there's no functional
@ -1835,10 +1835,10 @@ int sub(int *INPUT, int *INPUT);</pre>
<p>In Ruby, this allows you to pass simple values. For example:</p> <p>In Ruby, this allows you to pass simple values. For example:</p>
<div class="code targetlang"> <div class="code targetlang">
<pre>a = Example.add(3,4) <pre>a = Example.add(3, 4)
puts a puts a
7 7
b = Example.sub(7,4) b = Example.sub(7, 4)
puts b puts b
3</pre> 3</pre>
</div> </div>
@ -2086,7 +2086,7 @@ public:
<p> Then, in ruby, it can be used like:</p> <p> Then, in ruby, it can be used like:</p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
Window.new(0,0,360,480) { |w| Window.new(0, 0, 360, 480) { |w|
w.color = Fltk::RED w.color = Fltk::RED
w.border = false w.border = false
} }
@ -2102,7 +2102,7 @@ a special in typemap, like:</p>
// //
// void func(int x); // void func(int x);
%typemap(in,numinputs=0) int RUBY_YIELD_SELF { %typemap(in, numinputs=0) int RUBY_YIELD_SELF {
if ( !rb_block_given_p() ) if ( !rb_block_given_p() )
rb_raise("No block given"); rb_raise("No block given");
return rb_yield(self); return rb_yield(self);
@ -2384,7 +2384,7 @@ from Ruby to C, you might define a typemap like this: </p>
%typemap(in) int { %typemap(in) int {
$1 = (int) NUM2INT($input); $1 = (int) NUM2INT($input);
printf("Received an integer : %d\n",$1); printf("Received an integer : %d\n", $1);
} }
%inline %{ %inline %{
@ -2428,7 +2428,7 @@ supplying an optional parameter name. For example: </p>
%typemap(in) int n { %typemap(in) int n {
$1 = (int) NUM2INT($input); $1 = (int) NUM2INT($input);
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
%inline %{ %inline %{
@ -2450,7 +2450,7 @@ declarations. For example: </p>
<div class="code"> <div class="code">
<pre>%typemap(in) int n { <pre>%typemap(in) int n {
$1 = (int) NUM2INT($input); $1 = (int) NUM2INT($input);
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
typedef int Integer; typedef int Integer;
@ -2478,7 +2478,7 @@ always handled as a single Ruby object. This allows the function <tt>count</tt>
to be used as follows (notice how the length parameter is omitted): </p> to be used as follows (notice how the length parameter is omitted): </p>
<div class="code targetlang"> <div class="code targetlang">
<pre>puts Example.count('o','Hello World') <pre>puts Example.count('o', 'Hello World')
2</pre> 2</pre>
</div> </div>
@ -2747,7 +2747,7 @@ functions and methods. It merely checks an argument to see whether or
not it matches a specific type. For example:</p> not it matches a specific type. For example:</p>
<div class="code"> <div class="code">
<pre>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int { <pre>%typemap(typecheck, precedence=SWIG_TYPECHECK_INTEGER) int {
$1 = FIXNUM_P($input) ? 1 : 0; $1 = FIXNUM_P($input) ? 1 : 0;
}</pre> }</pre>
</div> </div>
@ -2862,7 +2862,7 @@ arguments have been converted. For example:</p>
<div class="code"> <div class="code">
<pre>%typemap(check) int positive { <pre>%typemap(check) int positive {
if ($1 &lt;= 0) { if ($1 &lt;= 0) {
SWIG_exception(SWIG_ValueError,"Expected positive value."); SWIG_exception(SWIG_ValueError, "Expected positive value.");
} }
}</pre> }</pre>
</div> </div>
@ -3168,7 +3168,7 @@ directive. Thus, a function can be made to return "nothing"
if you do:</p> if you do:</p>
<div class="code"><pre> <div class="code"><pre>
%feature("numoutputs","0") MyClass::function; %feature("numoutputs", "0") MyClass::function;
</pre></div> </pre></div>
<p>This feature can be useful if a function returns a status <p>This feature can be useful if a function returns a status
@ -3346,7 +3346,7 @@ across multiple languages.</p>
</tr> </tr>
<tr> <tr>
<td>rb_float_new(double) </td> <td>rb_float_new(double) </td>
<td>SWIG_From_double(double),<br> <td>SWIG_From_double(double), <br>
SWIG_From_float(float)</td> SWIG_From_float(float)</td>
<td>float/double to Float</td> <td>float/double to Float</td>
</tr> </tr>
@ -3365,7 +3365,7 @@ versions do not, but return a status value to indicate success (<tt>SWIG_OK</tt>
%typemap(in) size_t (int ok) %typemap(in) size_t (int ok)
ok = SWIG_AsVal_size_t($input, &amp;$1); ok = SWIG_AsVal_size_t($input, &amp;$1);
if (!SWIG_IsOK(ok)) { if (!SWIG_IsOK(ok)) {
SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input)); SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError( "$1_name", "$1_type", "$symname", $argnum, $input));
} }
} }
</pre> </pre>
@ -3615,7 +3615,7 @@ Array instance to be used as a <tt>char **</tt> object. </p>
int print_args(char **argv) { int print_args(char **argv) {
int i = 0; int i = 0;
while (argv[i]) { while (argv[i]) {
printf("argv[%d] = %s\n", i,argv[i]); printf("argv[%d] = %s\n", i, argv[i]);
i++; i++;
} }
return i; return i;
@ -3628,7 +3628,7 @@ operates as follows : </p>
<div class="code targetlang"> <div class="code targetlang">
<pre>require 'Argv' <pre>require 'Argv'
Argv.print_args(["Dave","Mike","Mary","Jane","John"]) Argv.print_args(["Dave", "Mike", "Mary", "Jane", "John"])
argv[0] = Dave argv[0] = Dave
argv[1] = Mike argv[1] = Mike
argv[2] = Mary argv[2] = Mary
@ -4591,7 +4591,7 @@ comma-separated list of module names to the <tt>%mixin</tt>
directive, e.g. </p> directive, e.g. </p>
<div class="code"> <div class="code">
<pre>%mixin Set "Fee,Fi,Fo,Fum";</pre> <pre>%mixin Set "Fee, Fi, Fo, Fum";</pre>
</div> </div>
<p> Note that the <tt>%mixin</tt> directive is <p> Note that the <tt>%mixin</tt> directive is
@ -4941,7 +4941,7 @@ in SWIG-1.3.26. and later.</p>
SWIG automatically keeps track of mappings between C++ objects and Ruby SWIG automatically keeps track of mappings between C++ objects and Ruby
objects. Note that enabling object tracking causes a slight performance objects. Note that enabling object tracking causes a slight performance
degradation. Test results show this degradation to be about 3% to 5% degradation. Test results show this degradation to be about 3% to 5%
when creating and destroying 100,000 animals in a row.</p> when creating and destroying 100, 000 animals in a row.</p>
<p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>, <p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>,
it uses the same name matching rules as other kinds of features (see it uses the same name matching rules as other kinds of features (see

View file

@ -480,7 +480,7 @@ Or in Python:
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; example.sin(3) &gt;&gt;&gt; example.sin(3)
5.2335956 5.2335956
&gt;&gt;&gt; example.strcmp('Dave','Mike') &gt;&gt;&gt; example.strcmp('Dave', 'Mike')
-1 -1
&gt;&gt;&gt; print example.cvar.Foo &gt;&gt;&gt; print example.cvar.Foo
42 42
@ -649,7 +649,7 @@ print cvar.foo # Print value of foo
# Perl # Perl
$foo = 3.5; # Set foo to 3.5 $foo = 3.5; # Set foo to 3.5
print $foo,"\n"; # Print value of foo print $foo, "\n"; # Print value of foo
# Ruby # Ruby
Module.foo = 3.5 # Set foo to 3.5 Module.foo = 3.5 # Set foo to 3.5
@ -750,7 +750,7 @@ form of type-checking however).</p>
<p> <p>
For enumerations, it is critical that the original enum definition be For enumerations, it is critical that the original enum definition be
included somewhere in the interface file (either in a header file or included somewhere in the interface file (either in a header file or
in the <tt>%{,%}</tt> block). SWIG only translates the enumeration in the <tt>%{, %}</tt> block). SWIG only translates the enumeration
into code needed to add the constants to a scripting language. It into code needed to add the constants to a scripting language. It
needs the original enumeration declaration in order to get the correct needs the original enumeration declaration in order to get the correct
enum values as assigned by the C compiler. enum values as assigned by the C compiler.
@ -1042,14 +1042,14 @@ expect :</p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
# Copy a file # Copy a file
def filecopy(source,target): def filecopy(source, target):
f1 = fopen(source,"r") f1 = fopen(source, "r")
f2 = fopen(target,"w") f2 = fopen(target, "w")
buffer = malloc(8192) buffer = malloc(8192)
nbytes = fread(buffer,8192,1,f1) nbytes = fread(buffer, 8192, 1, f1)
while (nbytes &gt; 0): while (nbytes &gt; 0):
fwrite(buffer,8192,1,f2) fwrite(buffer, 8192, 1, f2)
nbytes = fread(buffer,8192,1,f1) nbytes = fread(buffer, 8192, 1, f1)
free(buffer) free(buffer)
</pre></div> </pre></div>
@ -1238,7 +1238,7 @@ creating a wrapper equivalent to the following:
double wrap_dot_product(Vector *a, Vector *b) { double wrap_dot_product(Vector *a, Vector *b) {
Vector x = *a; Vector x = *a;
Vector y = *b; Vector y = *b;
return dot_product(x,y); return dot_product(x, y);
} }
</pre></div> </pre></div>
@ -1270,7 +1270,7 @@ Vector *wrap_cross_product(Vector *v1, Vector *v2) {
Vector y = *v2; Vector y = *v2;
Vector *result; Vector *result;
result = (Vector *) malloc(sizeof(Vector)); result = (Vector *) malloc(sizeof(Vector));
*(result) = cross(x,y); *(result) = cross(x, y);
return result; return result;
} }
</pre></div> </pre></div>
@ -1282,7 +1282,7 @@ or if SWIG was run with the <tt>-c++</tt> option:</p>
Vector *wrap_cross(Vector *v1, Vector *v2) { Vector *wrap_cross(Vector *v1, Vector *v2) {
Vector x = *v1; Vector x = *v1;
Vector y = *v2; Vector y = *v2;
Vector *result = new Vector(cross(x,y)); // Uses default copy constructor Vector *result = new Vector(cross(x, y)); // Uses default copy constructor
return result; return result;
} }
</pre></div> </pre></div>
@ -1360,14 +1360,14 @@ SWIG generates the following code:
void foo_set(char *value) { void foo_set(char *value) {
if (foo) free(foo); if (foo) free(foo);
foo = (char *) malloc(strlen(value)+1); foo = (char *) malloc(strlen(value)+1);
strcpy(foo,value); strcpy(foo, value);
} }
/* C++ mode. When -c++ option is used */ /* C++ mode. When -c++ option is used */
void foo_set(char *value) { void foo_set(char *value) {
if (foo) delete [] foo; if (foo) delete [] foo;
foo = new char[strlen(value)+1]; foo = new char[strlen(value)+1];
strcpy(foo,value); strcpy(foo, value);
} }
</pre> </pre>
</div> </div>
@ -1382,7 +1382,7 @@ exactly like you want. For example:
<pre> <pre>
%inline %{ %inline %{
void set_foo(char *value) { void set_foo(char *value) {
strncpy(foo,value, 50); strncpy(foo, value, 50);
} }
%} %}
</pre> </pre>
@ -1591,7 +1591,7 @@ char *pathname_get() {
return pathname; return pathname;
} }
void pathname_set(char *value) { void pathname_set(char *value) {
strncpy(pathname,value,256); strncpy(pathname, value, 256);
} }
</pre> </pre>
</div> </div>
@ -1612,9 +1612,9 @@ directive as shown :</p>
int a; // Can read/write int a; // Can read/write
%immutable; %immutable;
int b,c,d; // Read only variables int b, c, d; // Read only variables
%mutable; %mutable;
double x,y; // read/write double x, y; // read/write
</pre></div> </pre></div>
<p> <p>
@ -1639,7 +1639,7 @@ The <tt>%mutable</tt> and <tt>%immutable</tt> directives are actually
<div class="code"><pre> <div class="code"><pre>
#define %immutable %feature("immutable") #define %immutable %feature("immutable")
#define %mutable %feature("immutable","") #define %mutable %feature("immutable", "")
</pre></div> </pre></div>
<p> <p>
@ -1648,7 +1648,7 @@ If you wanted to make all wrapped variables read-only, barring one or two, it mi
<div class="code"><pre> <div class="code"><pre>
%immutable; // Make all variables read-only %immutable; // Make all variables read-only
%feature("immutable","0") x; // except, make x read/write %feature("immutable", "0") x; // except, make x read/write
... ...
double x; double x;
double y; double y;
@ -2173,7 +2173,7 @@ consider a function like this:
</p> </p>
<div class="code"><pre> <div class="code"><pre>
int binary_op(int a, int b, int (*op)(int,int)); int binary_op(int a, int b, int (*op)(int, int));
</pre></div> </pre></div>
<p> <p>
@ -2182,10 +2182,10 @@ may find the function to be impossible to use. For instance, in Python:
</p> </p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; def add(x,y): &gt;&gt;&gt; def add(x, y):
... return x+y ... return x+y
... ...
&gt;&gt;&gt; binary_op(3,4,add) &gt;&gt;&gt; binary_op(3, 4, add)
Traceback (most recent call last): Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ? File "&lt;stdin&gt;", line 1, in ?
TypeError: Type error. Expected _p_f_int_int__int TypeError: Type error. Expected _p_f_int_int__int
@ -2202,12 +2202,12 @@ One way to do this is to use the <tt>%constant</tt> directive like this:
<div class="code"><pre> <div class="code"><pre>
/* Function with a callback */ /* Function with a callback */
int binary_op(int a, int b, int (*op)(int,int)); int binary_op(int a, int b, int (*op)(int, int));
/* Some callback functions */ /* Some callback functions */
%constant int add(int,int); %constant int add(int, int);
%constant int sub(int,int); %constant int sub(int, int);
%constant int mul(int,int); %constant int mul(int, int);
</pre></div> </pre></div>
<p> <p>
@ -2217,9 +2217,9 @@ constants in the target scripting language. This allows you to use them as foll
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; binary_op(3,4,add) &gt;&gt;&gt; binary_op(3, 4, add)
7 7
&gt;&gt;&gt; binary_op(3,4,mul) &gt;&gt;&gt; binary_op(3, 4, mul)
12 12
&gt;&gt;&gt; &gt;&gt;&gt;
</pre> </pre>
@ -2232,7 +2232,7 @@ as functions. For example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; add(3,4) &gt;&gt;&gt; add(3, 4)
Traceback (most recent call last): Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ? File "&lt;stdin&gt;", line 1, in ?
TypeError: object is not callable: '_ff020efc_p_f_int_int__int' TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
@ -2248,13 +2248,13 @@ can use the <tt>%callback</tt> and <tt>%nocallback</tt> directives like this:
<div class="code"> <div class="code">
<pre> <pre>
/* Function with a callback */ /* Function with a callback */
int binary_op(int a, int b, int (*op)(int,int)); int binary_op(int a, int b, int (*op)(int, int));
/* Some callback functions */ /* Some callback functions */
%callback("%s_cb"); %callback("%s_cb");
int add(int,int); int add(int, int);
int sub(int,int); int sub(int, int);
int mul(int,int); int mul(int, int);
%nocallback; %nocallback;
</pre></div> </pre></div>
@ -2267,13 +2267,13 @@ disabled using <tt>%nocallback</tt>. When you do this, the interface now works
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; binary_op(3,4,add_cb) &gt;&gt;&gt; binary_op(3, 4, add_cb)
7 7
&gt;&gt;&gt; binary_op(3,4,mul_cb) &gt;&gt;&gt; binary_op(3, 4, mul_cb)
12 12
&gt;&gt;&gt; add(3,4) &gt;&gt;&gt; add(3, 4)
7 7
&gt;&gt;&gt; mul(3,4) &gt;&gt;&gt; mul(3, 4)
12 12
</pre> </pre>
</div> </div>
@ -2294,9 +2294,9 @@ variation installs the callbacks as all upper case constants such as
<div class="code"><pre> <div class="code"><pre>
/* Some callback functions */ /* Some callback functions */
%callback("%(uppercase)s"); %callback("%(uppercase)s");
int add(int,int); int add(int, int);
int sub(int,int); int sub(int, int);
int mul(int,int); int mul(int, int);
%nocallback; %nocallback;
</pre></div> </pre></div>
@ -2332,7 +2332,7 @@ to an individual member. For example, the declaration :</p>
<div class="code"><pre> <div class="code"><pre>
struct Vector { struct Vector {
double x,y,z; double x, y, z;
} }
</pre></div> </pre></div>
@ -2368,7 +2368,7 @@ defined in the interface. For example:
<div class="code"><pre> <div class="code"><pre>
struct Vector *new_Vector() { struct Vector *new_Vector() {
return (Vector *) calloc(1,sizeof(struct Vector)); return (Vector *) calloc(1, sizeof(struct Vector));
} }
void delete_Vector(struct Vector *obj) { void delete_Vector(struct Vector *obj) {
free(obj); free(obj);
@ -2384,9 +2384,9 @@ language using code like this:
<div class="code"> <div class="code">
<pre> <pre>
v = new_Vector() v = new_Vector()
Vector_x_set(v,2) Vector_x_set(v, 2)
Vector_y_set(v,10) Vector_y_set(v, 10)
Vector_z_set(v,-5) Vector_z_set(v, -5)
... ...
delete_Vector(v) delete_Vector(v)
</pre> </pre>
@ -2405,7 +2405,7 @@ programs :</p>
<div class="code"><pre> <div class="code"><pre>
typedef struct { typedef struct {
double x,y,z; double x, y, z;
} Vector; } Vector;
</pre></div> </pre></div>
@ -2430,7 +2430,7 @@ If two different names are used like this :</p>
<div class="code"><pre> <div class="code"><pre>
typedef struct vector_struct { typedef struct vector_struct {
double x,y,z; double x, y, z;
} Vector; } Vector;
</pre></div> </pre></div>
@ -2474,7 +2474,7 @@ char *Foo_name_set(Foo *obj, char *c) {
if (obj-&gt;name) if (obj-&gt;name)
free(obj-&gt;name); free(obj-&gt;name);
obj-&gt;name = (char *) malloc(strlen(c)+1); obj-&gt;name = (char *) malloc(strlen(c)+1);
strcpy(obj-&gt;name,c); strcpy(obj-&gt;name, c);
return obj-&gt;name; return obj-&gt;name;
} }
</pre></div> </pre></div>
@ -2571,7 +2571,7 @@ language interface) results in the following code:
<div class="code"> <div class="code">
<pre> <pre>
Bar *b; Bar *b;
Foo_x_set(Bar_f_get(b),37); Foo_x_set(Bar_f_get(b), 37);
</pre> </pre>
</div> </div>
@ -2727,7 +2727,7 @@ the following declaration :</p>
/* file : vector.h */ /* file : vector.h */
... ...
typedef struct Vector { typedef struct Vector {
double x,y,z; double x, y, z;
} Vector; } Vector;
</pre></div> </pre></div>
@ -2760,7 +2760,7 @@ You can make a <tt>Vector</tt> look a lot like a class by writing a SWIG interfa
return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z); return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z);
} }
void print() { void print() {
printf("Vector [%g, %g, %g]\n", $self-&gt;x,$self-&gt;y,$self-&gt;z); printf("Vector [%g, %g, %g]\n", $self-&gt;x, $self-&gt;y, $self-&gt;z);
} }
}; };
@ -2780,7 +2780,7 @@ Now, when used with proxy classes in Python, you can do things like
this :</p> this :</p>
<div class="targetlang"><pre> <div class="targetlang"><pre>
&gt;&gt;&gt; v = Vector(3,4,0) # Create a new vector &gt;&gt;&gt; v = Vector(3, 4, 0) # Create a new vector
&gt;&gt;&gt; print v.magnitude() # Print magnitude &gt;&gt;&gt; print v.magnitude() # Print magnitude
5.0 5.0
&gt;&gt;&gt; v.print() # Print it out &gt;&gt;&gt; v.print() # Print it out
@ -2800,7 +2800,7 @@ of the Vector structure. For example:</p>
%} %}
typedef struct Vector { typedef struct Vector {
double x,y,z; double x, y, z;
%extend { %extend {
Vector(double x, double y, double z) { ... } Vector(double x, double y, double z) { ... }
~Vector() { ... } ~Vector() { ... }
@ -2842,9 +2842,9 @@ double Vector_magnitude(Vector *v) {
%} %}
typedef struct Vector { typedef struct Vector {
double x,y,z; double x, y, z;
%extend { %extend {
Vector(int,int,int); // This calls new_Vector() Vector(int, int, int); // This calls new_Vector()
~Vector(); // This calls delete_Vector() ~Vector(); // This calls delete_Vector()
double magnitude(); // This will call Vector_magnitude() double magnitude(); // This will call Vector_magnitude()
... ...
@ -2959,7 +2959,7 @@ char *Person_name_get(Person *p) {
} }
void Person_name_set(Person *p, char *val) { void Person_name_set(Person *p, char *val) {
strncpy(p-&gt;name,val,50); strncpy(p-&gt;name, val, 50);
make_upper(p-&gt;name); make_upper(p-&gt;name);
} }
%} %}
@ -3104,11 +3104,11 @@ _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp,
struct Vector *arg1 ; struct Vector *arg1 ;
double result ; double result ;
if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&amp;arg0, if (SWIG_GetArgs(interp, objc, objv, "p:Vector_x_get self ", &amp;arg0,
SWIGTYPE_p_Vector) == TCL_ERROR) SWIGTYPE_p_Vector) == TCL_ERROR)
return TCL_ERROR; return TCL_ERROR;
result = (double ) (arg1-&gt;x); result = (double ) (arg1-&gt;x);
Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result)); Tcl_SetObjResult(interp, Tcl_NewDoubleObj((double) result));
return TCL_OK; return TCL_OK;
} }
</pre> </pre>
@ -3442,7 +3442,7 @@ header files.
<p> <p>
Sometimes, it is necessary to use certain header files in order for Sometimes, it is necessary to use certain header files in order for
the code generated by SWIG to compile properly. Make sure you the code generated by SWIG to compile properly. Make sure you
include certain header files by using a <tt>%{,%}</tt> block like this: include certain header files by using a <tt>%{, %}</tt> block like this:
</p> </p>
<div class="code"><pre> <div class="code"><pre>

View file

@ -282,13 +282,13 @@ class FooProxy {
delete_Foo(self); delete_Foo(self);
} }
int bar(int x) { int bar(int x) {
return Foo_bar(self,x); return Foo_bar(self, x);
} }
int x_get() { int x_get() {
return Foo_x_get(self); return Foo_x_get(self);
} }
void x_set(int x) { void x_set(int x) {
Foo_x_set(self,x); Foo_x_set(self, x);
} }
}; };
</pre> </pre>
@ -306,15 +306,15 @@ class Foo:
self.this = new_Foo() self.this = new_Foo()
def __del__(self): def __del__(self):
delete_Foo(self.this) delete_Foo(self.this)
def bar(self,x): def bar(self, x):
return Foo_bar(self.this,x) return Foo_bar(self.this, x)
def __getattr__(self,name): def __getattr__(self, name):
if name == 'x': if name == 'x':
return Foo_x_get(self.this) return Foo_x_get(self.this)
... ...
def __setattr__(self,name,value): def __setattr__(self, name, value):
if name == 'x': if name == 'x':
Foo_x_set(self.this,value) Foo_x_set(self.this, value)
... ...
</pre> </pre>
</div> </div>
@ -442,7 +442,7 @@ class SpamProxy {
return FooPtrProxy(Spam_value_get(self)); return FooPtrProxy(Spam_value_get(self));
} }
void value_set(FooProxy *v) { void value_set(FooProxy *v) {
Spam_value_set(self,v-&gt;self); Spam_value_set(self, v-&gt;self);
v-&gt;disown(); v-&gt;disown();
} }
... ...
@ -1435,7 +1435,7 @@ following:
Vector *wrap_cross_product(Vector *a, Vector *b) { Vector *wrap_cross_product(Vector *a, Vector *b) {
Vector x = *a; Vector x = *a;
Vector y = *b; Vector y = *b;
Vector r = cross_product(x,y); Vector r = cross_product(x, y);
return new Vector(r); return new Vector(r);
}</pre> }</pre>
</div> </div>
@ -1457,7 +1457,7 @@ called the "Fulton Transform". This produces a wrapper that looks like this:
Vector cross_product(Vector *a, Vector *b) { Vector cross_product(Vector *a, Vector *b) {
SwigValueWrapper&lt;Vector&gt; x = *a; SwigValueWrapper&lt;Vector&gt; x = *a;
SwigValueWrapper&lt;Vector&gt; y = *b; SwigValueWrapper&lt;Vector&gt; y = *b;
SwigValueWrapper&lt;Vector&gt; r = cross_product(x,y); SwigValueWrapper&lt;Vector&gt; r = cross_product(x, y);
return new Vector(r); return new Vector(r);
} }
</pre> </pre>
@ -1550,7 +1550,7 @@ the full C++ code has been omitted.</p>
class Shape { class Shape {
public: public:
double x,y; double x, y;
virtual double area() = 0; virtual double area() = 0;
virtual double perimeter() = 0; virtual double perimeter() = 0;
void set_location(double x, double y); void set_location(double x, double y);
@ -1586,7 +1586,7 @@ $ python
153.93804004599999757 153.93804004599999757
&gt;&gt;&gt; print shapes.Shape_area(square) &gt;&gt;&gt; print shapes.Shape_area(square)
100.00000000000000000 100.00000000000000000
&gt;&gt;&gt; shapes.Shape_set_location(square,2,-3) &gt;&gt;&gt; shapes.Shape_set_location(square, 2, -3)
&gt;&gt;&gt; print shapes.Shape_perimeter(square) &gt;&gt;&gt; print shapes.Shape_perimeter(square)
40.00000000000000000 40.00000000000000000
&gt;&gt;&gt; &gt;&gt;&gt;
@ -1892,7 +1892,7 @@ it might be used like this
&gt;&gt;&gt; f = Foo() # Create a Foo &gt;&gt;&gt; f = Foo() # Create a Foo
&gt;&gt;&gt; f.bar(3) &gt;&gt;&gt; f.bar(3)
&gt;&gt;&gt; g = Foo(f) # Copy Foo &gt;&gt;&gt; g = Foo(f) # Copy Foo
&gt;&gt;&gt; f.bar("hello",2) &gt;&gt;&gt; f.bar("hello", 2)
</pre> </pre>
</div> </div>
@ -2129,7 +2129,7 @@ If you get an error message such as the following,
<pre> <pre>
foo.i:6. Overloaded declaration ignored. Spam::foo(double ) foo.i:6. Overloaded declaration ignored. Spam::foo(double )
foo.i:5. Previous declaration is Spam::foo(int ) foo.i:5. Previous declaration is Spam::foo(int )
foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *,Spam *,int ) foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *, Spam *, int )
foo.i:5. Previous declaration is Spam::foo(int ) foo.i:5. Previous declaration is Spam::foo(int )
</pre> </pre>
</div> </div>
@ -2674,8 +2674,8 @@ operator normally. For example:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; a = Complex(3,4) &gt;&gt;&gt; a = Complex(3, 4)
&gt;&gt;&gt; b = Complex(5,2) &gt;&gt;&gt; b = Complex(5, 2)
&gt;&gt;&gt; c = a + b # Invokes __add__ method &gt;&gt;&gt; c = a + b # Invokes __add__ method
</pre> </pre>
</div> </div>
@ -2698,8 +2698,8 @@ The resulting scripting interface might work like this:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
a = Complex(3,4) a = Complex(3, 4)
b = Complex(5,2) b = Complex(5, 2)
c = a.add(b) # Call a.operator+(b) c = a.add(b) # Call a.operator+(b)
</pre> </pre>
</div> </div>
@ -2807,14 +2807,14 @@ example :
class Vector { class Vector {
public: public:
double x,y,z; double x, y, z;
Vector(); Vector();
~Vector(); ~Vector();
... bunch of C++ methods ... ... bunch of C++ methods ...
%extend { %extend {
char *__str__() { char *__str__() {
static char temp[256]; static char temp[256];
sprintf(temp,"[ %g, %g, %g ]", $self-&gt;x,$self-&gt;y,$self-&gt;z); sprintf(temp, "[ %g, %g, %g ]", $self-&gt;x, $self-&gt;y, $self-&gt;z);
return &amp;temp[0]; return &amp;temp[0];
} }
} }
@ -2899,7 +2899,7 @@ is expected in an interface file. For example:
<div class="code"> <div class="code">
<pre> <pre>
void foo(vector&lt;int&gt; *a, int n); void foo(vector&lt;int&gt; *a, int n);
void bar(list&lt;int,100&gt; *x); void bar(list&lt;int, 100&gt; *x);
</pre> </pre>
</div> </div>
@ -2912,9 +2912,9 @@ and '&gt;' within a constant expressions currently is not supported by SWIG
<div class="code"> <div class="code">
<pre> <pre>
void bar(list&lt;int,100&gt; *x); // OK void bar(list&lt;int, 100&gt; *x); // OK
void bar(list&lt;int,2*50&gt; *x); // OK void bar(list&lt;int, 2*50&gt; *x); // OK
void bar(list&lt;int,(2&gt;1 ? 100 : 50)&gt; *x) // Not supported void bar(list&lt;int, (2&gt;1 ? 100 : 50)&gt; *x) // Not supported
</pre> </pre>
</div> </div>
@ -3085,7 +3085,7 @@ template vector&lt;typename T, int max=100&gt; class vector {
}; };
%template(intvec) vector&lt;int&gt;; // OK %template(intvec) vector&lt;int&gt;; // OK
%template(vec1000) vector&lt;int,1000&gt;; // OK %template(vec1000) vector&lt;int, 1000&gt;; // OK
</pre> </pre>
</div> </div>
@ -3205,8 +3205,8 @@ use the empty template instantiation, that is, <tt>%template</tt> with no name.
<div class="code"> <div class="code">
<pre> <pre>
// Instantiate traits&lt;double,double&gt;, but don't wrap it. // Instantiate traits&lt;double, double&gt;, but don't wrap it.
%template() traits&lt;double,double&gt;; %template() traits&lt;double, double&gt;;
</pre> </pre>
</div> </div>
@ -3466,8 +3466,8 @@ template&lt;class T1, class T2&gt; struct pair {
T2 second; T2 second;
pair() : first(T1()), second(T2()) { } pair() : first(T1()), second(T2()) { }
pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { } pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
template&lt;class U1, class U2&gt; pair(const pair&lt;U1,U2&gt; &amp;x) template&lt;class U1, class U2&gt; pair(const pair&lt;U1, U2&gt; &amp;x)
: first(x.first),second(x.second) { } : first(x.first), second(x.second) { }
}; };
</pre> </pre>
</div> </div>
@ -3481,7 +3481,7 @@ in the template class itself. For example:
<div class="code"> <div class="code">
<pre> <pre>
%extend pair { %extend pair {
%template(pair) pair&lt;T1,T2&gt;; // Generate default copy constructor %template(pair) pair&lt;T1, T2&gt;; // Generate default copy constructor
}; };
</pre> </pre>
</div> </div>
@ -3498,18 +3498,18 @@ Alternatively, you could expand the constructor template in selected instantiati
<div class="code"> <div class="code">
<pre> <pre>
// Instantiate a few versions // Instantiate a few versions
%template(pairii) pair&lt;int,int&gt;; %template(pairii) pair&lt;int, int&gt;;
%template(pairdd) pair&lt;double,double&gt;; %template(pairdd) pair&lt;double, double&gt;;
// Create a default constructor only // Create a default constructor only
%extend pair&lt;int,int&gt; { %extend pair&lt;int, int&gt; {
%template(paird) pair&lt;int,int&gt;; // Default constructor %template(paird) pair&lt;int, int&gt;; // Default constructor
}; };
// Create default and conversion constructors // Create default and conversion constructors
%extend pair&lt;double,double&gt; { %extend pair&lt;double, double&gt; {
%template(paird) pair&lt;double,dobule&gt;; // Default constructor %template(paird) pair&lt;double, dobule&gt;; // Default constructor
%template(pairc) pair&lt;int,int&gt;; // Conversion constructor %template(pairc) pair&lt;int, int&gt;; // Conversion constructor
}; };
</pre> </pre>
</div> </div>
@ -3522,9 +3522,9 @@ instead:
<div class="code"> <div class="code">
<pre> <pre>
// Create default and conversion constructors // Create default and conversion constructors
%extend pair&lt;double,double&gt; { %extend pair&lt;double, double&gt; {
%template(pair) pair&lt;double,dobule&gt;; // Default constructor %template(pair) pair&lt;double, dobule&gt;; // Default constructor
%template(pair) pair&lt;int,int&gt;; // Conversion constructor %template(pair) pair&lt;int, int&gt;; // Conversion constructor
}; };
</pre> </pre>
</div> </div>
@ -3745,7 +3745,7 @@ namespace math {
double cos(double); double cos(double);
class Complex { class Complex {
double im,re; double im, re;
public: public:
... ...
}; };
@ -4364,7 +4364,7 @@ write code like this:
f = Foo() f = Foo()
try: try:
f.blah() f.blah()
except Error,e: except Error, e:
# e is a wrapped instance of "Error" # e is a wrapped instance of "Error"
</pre> </pre>
</div> </div>
@ -4403,14 +4403,14 @@ struct Error2 : EBase { };
struct Error3 : EBase { }; struct Error3 : EBase { };
struct Error4 : EBase { }; struct Error4 : EBase { };
%catches(Error1,Error2,...) Foo::bar(); %catches(Error1, Error2, ...) Foo::bar();
%catches(EBase) Foo::blah(); %catches(EBase) Foo::blah();
class Foo { class Foo {
public: public:
... ...
void bar(); void bar();
void blah() throw(Error1,Error2,Error3,Error4); void blah() throw(Error1, Error2, Error3, Error4);
... ...
}; };
</pre> </pre>
@ -4441,9 +4441,9 @@ For example:
<div class="code"> <div class="code">
<pre> <pre>
double do_op(Object *o, double (Object::*callback)(double,double)); double do_op(Object *o, double (Object::*callback)(double, double));
extern double (Object::*fooptr)(double,double); extern double (Object::*fooptr)(double, double);
%constant double (Object::*FOO)(double,double) = &amp;Object::foo; %constant double (Object::*FOO)(double, double) = &amp;Object::foo;
</pre> </pre>
</div> </div>

View file

@ -1243,7 +1243,7 @@ struct triplet {
} }
}; };
%template(IntTriplet) triplet&lt;int,int,int&gt;; %template(IntTriplet) triplet&lt;int, int, int&gt;;
</pre></div> </pre></div>
<p> <p>
@ -1321,7 +1321,7 @@ private:
<div class="targetlang"><pre> <div class="targetlang"><pre>
--&gt; c1 = new_Complex(3, 7); --&gt; c1 = new_Complex(3, 7);
--&gt; c2 = Complex_plus(c, new_Complex(1,1)); --&gt; c2 = Complex_plus(c, new_Complex(1, 1));
--&gt; Complex_toDouble(c2) --&gt; Complex_toDouble(c2)
ans = ans =
@ -1355,7 +1355,7 @@ namespace foo {
} }
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
}; };
@ -1636,17 +1636,17 @@ double **create_matrix() {
return M; return M;
} }
// Gets the item M(i,j) value // Gets the item M(i, j) value
double get_matrix(double **M, int i, int j) { double get_matrix(double **M, int i, int j) {
return M[i][j]; return M[i][j];
} }
// Sets the item M(i,j) value to be val // Sets the item M(i, j) value to be val
void set_matrix(double **M, int i, int j, double val) { void set_matrix(double **M, int i, int j, double val) {
M[i][j] = val; M[i][j] = val;
} }
// Prints a matrix (2,2) to console // Prints a matrix (2, 2) to console
void print_matrix(double **M, int nbRows, int nbCols) { void print_matrix(double **M, int nbRows, int nbCols) {
int i, j; int i, j;
for (i = 0; i &lt; 2; i++) { for (i = 0; i &lt; 2; i++) {
@ -1769,7 +1769,7 @@ void absolute(int *matrix, int matrixNbRow, int matrixNbCol,
The remarks made earlier for arrays also apply here: The remarks made earlier for arrays also apply here:
</p> </p>
<ul> <ul>
<li>The values of matrices in Scilab are column-major orderered,</li> <li>The values of matrices in Scilab are column-major orderered, </li>
<li>There is no control while converting <tt>double</tt> values to integers, <tt>double</tt> values are truncated without any checking or warning.</li> <li>There is no control while converting <tt>double</tt> values to integers, <tt>double</tt> values are truncated without any checking or warning.</li>
</ul> </ul>
@ -2062,7 +2062,7 @@ The command is:
</p> </p>
<div class="shell"><pre> <div class="shell"><pre>
$ swig -scilab -builder -buildercflags -I/opt/foo/include -builderldflags "-L/opt/foo/lib -lfoo" -buildersources baa1.cxx,baa2.cxx example.i $ swig -scilab -builder -buildercflags -I/opt/foo/include -builderldflags "-L/opt/foo/lib -lfoo" -buildersources baa1.cxx, baa2.cxx example.i
</pre></div> </pre></div>
<H2><a name="Scilab_generated_scripts">39.7 Generated scripts</a></H2> <H2><a name="Scilab_generated_scripts">39.7 Generated scripts</a></H2>
@ -2082,12 +2082,12 @@ In this part we give some details about the generated Scilab scripts.
ilib_name = "examplelib"; ilib_name = "examplelib";
files = ["example_wrap.c"]; files = ["example_wrap.c"];
libs = []; libs = [];
table = ["fact","_wrap_fact";"Foo_set","_wrap_Foo_set";"Foo_get","_wrap_Foo_get";]; table = ["fact", "_wrap_fact";"Foo_set", "_wrap_Foo_set";"Foo_get", "_wrap_Foo_get";];
ilib_build(ilib_name,table,files,libs); ilib_build(ilib_name, table, files, libs);
</pre></div> </pre></div>
<p> <p>
<tt>ilib_build(lib_name,table,files,libs)</tt> is used to create shared libraries, and to generate a loader file used to dynamically load the shared library into Scilab. <tt>ilib_build(lib_name, table, files, libs)</tt> is used to create shared libraries, and to generate a loader file used to dynamically load the shared library into Scilab.
</p> </p>
<ul> <ul>
@ -2118,7 +2118,7 @@ list_functions = [ 'fact';
'Foo_set'; 'Foo_set';
'Foo_get'; 'Foo_get';
]; ];
addinter(libexamplelib_path+'/libexamplelib.so','libexamplelib',list_functions); addinter(libexamplelib_path+'/libexamplelib.so', 'libexamplelib', list_functions);
// remove temp. variables on stack // remove temp. variables on stack
clear libexamplelib_path; clear libexamplelib_path;
clear list_functions; clear list_functions;
@ -2127,7 +2127,7 @@ clear get_file_path;
</pre></div> </pre></div>
<p> <p>
<tt>addinter(files,spname,fcts)</tt> performs dynamic linking of a compiled C interface function. <tt>addinter(files, spname, fcts)</tt> performs dynamic linking of a compiled C interface function.
</p> </p>
<ul> <ul>
<li><tt><b>files</b></tt>: a character string or a vector of character strings defining the object files (containing the C interface functions) to link with.</li> <li><tt><b>files</b></tt>: a character string or a vector of character strings defining the object files (containing the C interface functions) to link with.</li>

View file

@ -135,7 +135,7 @@ int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
} }
arg0 = atoi(argv[1]); arg0 = atoi(argv[1]);
result = fact(arg0); result = fact(arg0);
sprintf(interp-&gt;result,"%d", result); sprintf(interp-&gt;result, "%d", result);
return TCL_OK; return TCL_OK;
} }
@ -247,7 +247,7 @@ representation of a structure. For example,
struct Vector { struct Vector {
Vector(); Vector();
~Vector(); ~Vector();
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -302,7 +302,7 @@ class Vector {
public: public:
Vector(); Vector();
~Vector(); ~Vector();
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>

View file

@ -981,7 +981,7 @@ This provides a very natural interface. For example,
<div class="code"><pre> <div class="code"><pre>
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
</pre></div> </pre></div>
@ -1663,7 +1663,7 @@ submodules or packages. For example, if you have a file like this,
namespace foo { namespace foo {
int fact(int n); int fact(int n);
struct Vector { struct Vector {
double x,y,z; double x, y, z;
}; };
}; };
</pre> </pre>
@ -1739,7 +1739,7 @@ struct pair {
~pair(); ~pair();
}; };
%template(pairii) pair&lt;int,int&gt;; %template(pairii) pair&lt;int, int&gt;;
</pre> </pre>
</div> </div>
@ -2465,9 +2465,9 @@ you might define a typemap like this:
%module example %module example
%typemap(in) int { %typemap(in) int {
if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
return TCL_ERROR; return TCL_ERROR;
printf("Received an integer : %d\n",$1); printf("Received an integer : %d\n", $1);
} }
%inline %{ %inline %{
extern int fact(int n); extern int fact(int n);
@ -2504,9 +2504,9 @@ You can refine this by supplying an optional parameter name. For example:
%module example %module example
%typemap(in) int n { %typemap(in) int n {
if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
return TCL_ERROR; return TCL_ERROR;
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
%inline %{ %inline %{
extern int fact(int n); extern int fact(int n);
@ -2528,9 +2528,9 @@ the typemap system follows <tt>typedef</tt> declarations. For example:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(in) int n { %typemap(in) int n {
if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
return TCL_ERROR; return TCL_ERROR;
printf("n = %d\n",$1); printf("n = %d\n", $1);
} }
%inline %{ %inline %{
typedef int Integer; typedef int Integer;
@ -2552,7 +2552,7 @@ Typemaps can also be defined for groups of consecutive arguments. For example:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(in) (char *str, int len) { %typemap(in) (char *str, int len) {
$1 = Tcl_GetStringFromObj($input,&amp;$2); $1 = Tcl_GetStringFromObj($input, &amp;$2);
}; };
int count(char c, char *str, int len); int count(char c, char *str, int len);
@ -2585,7 +2585,7 @@ like this:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(out) int { %typemap(out) int {
Tcl_SetObjResult(interp,Tcl_NewIntObj($1)); Tcl_SetObjResult(interp, Tcl_NewIntObj($1));
} }
</pre> </pre>
</div> </div>
@ -2804,7 +2804,7 @@ used as a <tt>char **</tt> object.
} }
$1 = (char **) malloc((nitems+1)*sizeof(char *)); $1 = (char **) malloc((nitems+1)*sizeof(char *));
for (i = 0; i &lt; nitems; i++) { for (i = 0; i &lt; nitems; i++) {
$1[i] = Tcl_GetStringFromObj(listobjv[i],0); $1[i] = Tcl_GetStringFromObj(listobjv[i], 0);
} }
$1[i] = 0; $1[i] = 0;
} }
@ -2821,7 +2821,7 @@ used as a <tt>char **</tt> object.
int print_args(char **argv) { int print_args(char **argv) {
int i = 0; int i = 0;
while (argv[i]) { while (argv[i]) {
printf("argv[%d] = %s\n", i,argv[i]); printf("argv[%d] = %s\n", i, argv[i]);
i++; i++;
} }
return i; return i;
@ -2855,19 +2855,19 @@ function argument. For example :
// A typemap defining how to return an argument by appending it to the result // A typemap defining how to return an argument by appending it to the result
%typemap(argout) double *outvalue { %typemap(argout) double *outvalue {
Tcl_Obj *o = Tcl_NewDoubleObj($1); Tcl_Obj *o = Tcl_NewDoubleObj($1);
Tcl_ListObjAppendElement(interp,$result,o); Tcl_ListObjAppendElement(interp, $result, o);
} }
// A typemap telling SWIG to ignore an argument for input // A typemap telling SWIG to ignore an argument for input
// However, we still need to pass a pointer to the C function // However, we still need to pass a pointer to the C function
%typemap(in,numinputs=0) double *outvalue (double temp) { %typemap(in, numinputs=0) double *outvalue (double temp) {
$1 = &amp;temp; $1 = &amp;temp;
} }
// Now a function returning two values // Now a function returning two values
int mypow(double a, double b, double *outvalue) { int mypow(double a, double b, double *outvalue) {
if ((a &lt; 0) || (b &lt; 0)) return -1; if ((a &lt; 0) || (b &lt; 0)) return -1;
*outvalue = pow(a,b); *outvalue = pow(a, b);
return 0; return 0;
}; };
</pre></div> </pre></div>
@ -2991,7 +2991,7 @@ work)
<div class="code"> <div class="code">
<pre> <pre>
%typemap(out) int, short, long { %typemap(out) int, short, long {
Tcl_SetIntObj($result,(int) $1); Tcl_SetIntObj($result, (int) $1);
} }
</pre> </pre>
</div> </div>
@ -3038,8 +3038,8 @@ work)
<div class="code"> <div class="code">
<pre> <pre>
%typemap(out,noblock=1,fragment="SWIG_FromCharPtr") char *, const char * { %typemap(out, noblock=1, fragment="SWIG_FromCharPtr") char *, const char * {
Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)$1)); Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *)$1));
} }
</pre> </pre>

View file

@ -289,7 +289,7 @@ PyObject *wrap_gcd(PyObject *self, PyObject *args) {
arg2 = PyInt_AsLong(obj2); arg2 = PyInt_AsLong(obj2);
} }
</b> </b>
result = gcd(arg1,arg2); result = gcd(arg1, arg2);
/* "out" typemap, return value */<b> /* "out" typemap, return value */<b>
{ {
@ -375,7 +375,7 @@ example, you could write a typemap like this:
%typemap(in) <b>double nonnegative</b> { %typemap(in) <b>double nonnegative</b> {
$1 = PyFloat_AsDouble($input); $1 = PyFloat_AsDouble($input);
if ($1 &lt; 0) { if ($1 &lt; 0) {
PyErr_SetString(PyExc_ValueError,"argument must be nonnegative."); PyErr_SetString(PyExc_ValueError, "argument must be nonnegative.");
SWIG_fail; SWIG_fail;
} }
} }
@ -623,7 +623,7 @@ function like this:
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
foo("hello",3) # Reversed arguments foo("hello", 3) # Reversed arguments
</pre> </pre>
</div> </div>
@ -637,7 +637,7 @@ function instead. For example:
%rename(foo) wrap_foo; %rename(foo) wrap_foo;
%inline %{ %inline %{
void wrap_foo(char *s, int x) { void wrap_foo(char *s, int x) {
foo(x,s); foo(x, s);
} }
%} %}
</pre> </pre>
@ -777,7 +777,7 @@ Here are some examples of valid typemap specifications:
} }
/* Typemap with modifiers */ /* Typemap with modifiers */
%typemap(in,doc="integer") int "$1 = scm_to_int($input);"; %typemap(in, doc="integer") int "$1 = scm_to_int($input);";
/* Typemap applied to patterns of multiple arguments */ /* Typemap applied to patterns of multiple arguments */
%typemap(in) (char *str, int len), %typemap(in) (char *str, int len),
@ -1248,7 +1248,7 @@ like this:
<div class="code"> <div class="code">
<pre> <pre>
typedef int Integer; typedef int Integer;
typedef foo&lt;Integer,Integer&gt; fooii; typedef foo&lt;Integer, Integer&gt; fooii;
void blah(fooii *x); void blah(fooii *x);
</pre> </pre>
</div> </div>
@ -1262,9 +1262,9 @@ In this case, the following typemap patterns are searched for the argument <tt>f
fooii *x fooii *x
fooii * fooii *
# Reduce fooii --&gt; foo&lt;Integer,Integer&gt; # Reduce fooii --&gt; foo&lt;Integer, Integer&gt;
foo&lt;Integer,Integer&gt; *x foo&lt;Integer, Integer&gt; *x
foo&lt;Integer,Integer&gt; * foo&lt;Integer, Integer&gt; *
# Reduce Integer -&gt; int # Reduce Integer -&gt; int
foo&lt;int, Integer&gt; *x foo&lt;int, Integer&gt; *x
@ -1279,7 +1279,7 @@ foo&lt;int, int&gt; *
<p> <p>
Typemap reductions are always applied to the left-most type that appears. Only when no reductions can be made to the left-most Typemap reductions are always applied to the left-most type that appears. Only when no reductions can be made to the left-most
type are reductions made to other parts of the type. This behavior means that you could define a typemap for type are reductions made to other parts of the type. This behavior means that you could define a typemap for
<tt>foo&lt;int,Integer&gt;</tt>, but a typemap for <tt>foo&lt;Integer,int&gt;</tt> would never be matched. Admittedly, this <tt>foo&lt;int, Integer&gt;</tt>, but a typemap for <tt>foo&lt;Integer, int&gt;</tt> would never be matched. Admittedly, this
is rather esoteric--there's little practical reason to write a typemap quite like that. Of course, you could rely on this is rather esoteric--there's little practical reason to write a typemap quite like that. Of course, you could rely on this
to confuse your coworkers even more. to confuse your coworkers even more.
</p> </p>
@ -1714,7 +1714,7 @@ you'll find the full typemap contents (example shown below for Python):
<div class="code"> <div class="code">
<pre> <pre>
%typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) { %typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) {
res = SWIG_ConvertPtr($input, &amp;argp,$descriptor, $disown | 0 ); res = SWIG_ConvertPtr($input, &amp;argp, $descriptor, $disown | 0 );
if (!SWIG_IsOK(res)) { if (!SWIG_IsOK(res)) {
SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument "
"$argnum"" of type '" "$type""'"); "$argnum"" of type '" "$type""'");
@ -1736,7 +1736,7 @@ SWIGINTERN PyObject *_wrap_foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
void *argp1 = 0 ; void *argp1 = 0 ;
int res1 = 0 ; int res1 = 0 ;
... ...
res1 = SWIG_ConvertPtr(obj0, &amp;argp1,SWIGTYPE_p_a_4__int, 0 | 0 ); res1 = SWIG_ConvertPtr(obj0, &amp;argp1, SWIGTYPE_p_a_4__int, 0 | 0 );
if (!SWIG_IsOK(res1)) { if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "foo" "', argument " SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "foo" "', argument "
"1"" of type '" "int [10][4]""'"); "1"" of type '" "int [10][4]""'");
@ -1758,7 +1758,7 @@ For example, the output for the code in the <a href="#Typemaps_multi_argument_ty
example.h:39: Searching for a suitable 'in' typemap for: char *buffer example.h:39: Searching for a suitable 'in' typemap for: char *buffer
Looking for: char *buffer Looking for: char *buffer
Multi-argument typemap found... Multi-argument typemap found...
Using: %typemap(in) (char *buffer,int len) Using: %typemap(in) (char *buffer, int len)
... ...
</pre> </pre>
</div> </div>
@ -1968,8 +1968,8 @@ then pass a pointer to the object. To do this, simply specify the typemap with
%typemap(in) std::string * <b>(std::string temp)</b> { %typemap(in) std::string * <b>(std::string temp)</b> {
unsigned int len; unsigned int len;
char *s; char *s;
s = SvPV($input,len); /* Extract string data */ s = SvPV($input, len); /* Extract string data */
temp.assign(s,len); /* Assign to temp */ temp.assign(s, len); /* Assign to temp */
$1 = &amp;temp; /* Set argument to point to temp */ $1 = &amp;temp; /* Set argument to point to temp */
} }
</pre> </pre>
@ -1989,7 +1989,7 @@ wrap_foo() {
/* Typemap code */ /* Typemap code */
{ {
... ...
temp.assign(s,len); temp.assign(s, len);
... ...
} }
... ...
@ -2032,21 +2032,21 @@ wrap_foo() {
char *s; char *s;
unsigned int len; unsigned int len;
... ...
temp1.assign(s,len); temp1.assign(s, len);
arg1 = *temp1; arg1 = *temp1;
} }
{ {
char *s; char *s;
unsigned int len; unsigned int len;
... ...
temp2.assign(s,len); temp2.assign(s, len);
arg2 = &amp;temp2; arg2 = &amp;temp2;
} }
{ {
char *s; char *s;
unsigned int len; unsigned int len;
... ...
temp3.assign(s,len); temp3.assign(s, len);
arg3 = &amp;temp3; arg3 = &amp;temp3;
} }
... ...
@ -2577,7 +2577,7 @@ to see whether or not it matches a specific type. For example:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int { %typemap(typecheck, precedence=SWIG_TYPECHECK_INTEGER) int {
$1 = PyInt_Check($input) ? 1 : 0; $1 = PyInt_Check($input) ? 1 : 0;
} }
</pre> </pre>
@ -2690,7 +2690,7 @@ converted. For example:
<pre> <pre>
%typemap(check) int positive { %typemap(check) int positive {
if ($1 &lt;= 0) { if ($1 &lt;= 0) {
SWIG_exception(SWIG_ValueError,"Expected positive value."); SWIG_exception(SWIG_ValueError, "Expected positive value.");
} }
} }
</pre> </pre>
@ -2963,19 +2963,19 @@ similar to this:
%typemap(in) float value[4] (float temp[4]) { %typemap(in) float value[4] (float temp[4]) {
int i; int i;
if (!PySequence_Check($input)) { if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence"); PyErr_SetString(PyExc_ValueError, "Expected a sequence");
SWIG_fail; SWIG_fail;
} }
if (PySequence_Length($input) != 4) { if (PySequence_Length($input) != 4) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements"); PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected 4 elements");
SWIG_fail; SWIG_fail;
} }
for (i = 0; i &lt; 4; i++) { for (i = 0; i &lt; 4; i++) {
PyObject *o = PySequence_GetItem($input,i); PyObject *o = PySequence_GetItem($input, i);
if (PyNumber_Check(o)) { if (PyNumber_Check(o)) {
temp[i] = (float) PyFloat_AsDouble(o); temp[i] = (float) PyFloat_AsDouble(o);
} else { } else {
PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); PyErr_SetString(PyExc_ValueError, "Sequence elements must be numbers");
SWIG_fail; SWIG_fail;
} }
} }
@ -3008,19 +3008,19 @@ If you wanted to generalize the typemap to apply to arrays of all dimensions you
%typemap(in) float value[ANY] (float temp[$1_dim0]) { %typemap(in) float value[ANY] (float temp[$1_dim0]) {
int i; int i;
if (!PySequence_Check($input)) { if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence"); PyErr_SetString(PyExc_ValueError, "Expected a sequence");
SWIG_fail; SWIG_fail;
} }
if (PySequence_Length($input) != $1_dim0) { if (PySequence_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected $1_dim0 elements");
SWIG_fail; SWIG_fail;
} }
for (i = 0; i &lt; $1_dim0; i++) { for (i = 0; i &lt; $1_dim0; i++) {
PyObject *o = PySequence_GetItem($input,i); PyObject *o = PySequence_GetItem($input, i);
if (PyNumber_Check(o)) { if (PyNumber_Check(o)) {
temp[i] = (float) PyFloat_AsDouble(o); temp[i] = (float) PyFloat_AsDouble(o);
} else { } else {
PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); PyErr_SetString(PyExc_ValueError, "Sequence elements must be numbers");
SWIG_fail; SWIG_fail;
} }
} }
@ -3052,21 +3052,21 @@ as shown. To work with heap allocated data, the following technique can be use
%typemap(in) float value[ANY] { %typemap(in) float value[ANY] {
int i; int i;
if (!PySequence_Check($input)) { if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence"); PyErr_SetString(PyExc_ValueError, "Expected a sequence");
SWIG_fail; SWIG_fail;
} }
if (PySequence_Length($input) != $1_dim0) { if (PySequence_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected $1_dim0 elements");
SWIG_fail; SWIG_fail;
} }
$1 = (float *) malloc($1_dim0*sizeof(float)); $1 = (float *) malloc($1_dim0*sizeof(float));
for (i = 0; i &lt; $1_dim0; i++) { for (i = 0; i &lt; $1_dim0; i++) {
PyObject *o = PySequence_GetItem($input,i); PyObject *o = PySequence_GetItem($input, i);
if (PyNumber_Check(o)) { if (PyNumber_Check(o)) {
$1[i] = (float) PyFloat_AsDouble(o); $1[i] = (float) PyFloat_AsDouble(o);
} else { } else {
free($1); free($1);
PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); PyErr_SetString(PyExc_ValueError, "Sequence elements must be numbers");
SWIG_fail; SWIG_fail;
} }
} }
@ -3169,7 +3169,7 @@ To fix this, you can write an "out" typemap. For example:
$result = PyList_New($1_dim0); $result = PyList_New($1_dim0);
for (i = 0; i &lt; $1_dim0; i++) { for (i = 0; i &lt; $1_dim0; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]); PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o); PyList_SetItem($result, i, o);
} }
} }
</pre> </pre>
@ -3228,7 +3228,7 @@ pointers. For example:</p>
<div class="code"><pre> <div class="code"><pre>
%typemap(check) Vector * { %typemap(check) Vector * {
if ($1 == 0) { if ($1 == 0) {
PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed"); PyErr_SetString(PyExc_TypeError, "NULL Pointer not allowed");
SWIG_fail; SWIG_fail;
} }
} }
@ -3268,7 +3268,7 @@ The example above also shows a common approach of issuing a warning for an as ye
<p> <p>
<b>Compatibility note: </b> In SWIG-1.1 different languages could be distinguished with the language name being put within the <tt>%typemap</tt> directive, for example, <br> <b>Compatibility note: </b> In SWIG-1.1 different languages could be distinguished with the language name being put within the <tt>%typemap</tt> directive, for example, <br>
<tt>%typemap(ruby,in) int "$1 = NUM2INT($input);"</tt>. <tt>%typemap(ruby, in) int "$1 = NUM2INT($input);"</tt>.
</p> </p>
<H2><a name="Typemaps_optimal">11.8 Optimal code generation when returning by value</a></H2> <H2><a name="Typemaps_optimal">11.8 Optimal code generation when returning by value</a></H2>
@ -3513,7 +3513,7 @@ maps perform the conversion described for the above example:
$1 = PyList_Size($input); $1 = PyList_Size($input);
$2 = (char **) malloc(($1+1)*sizeof(char *)); $2 = (char **) malloc(($1+1)*sizeof(char *));
for (i = 0; i &lt; $1; i++) { for (i = 0; i &lt; $1; i++) {
PyObject *s = PyList_GetItem($input,i); PyObject *s = PyList_GetItem($input, i);
if (!PyString_Check(s)) { if (!PyString_Check(s)) {
free($2); free($2);
PyErr_SetString(PyExc_ValueError, "List items must be strings"); PyErr_SetString(PyExc_ValueError, "List items must be strings");
@ -3661,7 +3661,7 @@ might write typemaps like this:
PyErr_SetFromErrno(PyExc_IOError); PyErr_SetFromErrno(PyExc_IOError);
return NULL; return NULL;
} }
$result = PyString_FromStringAndSize($1,result); $result = PyString_FromStringAndSize($1, result);
free($1); free($1);
} }
</pre> </pre>
@ -3680,16 +3680,16 @@ Now, in a script, you can write code that simply passes buffers as strings like
<div class="targetlang"> <div class="targetlang">
<pre> <pre>
&gt;&gt;&gt; f = example.open("Makefile") &gt;&gt;&gt; f = example.open("Makefile")
&gt;&gt;&gt; example.read(f,40) &gt;&gt;&gt; example.read(f, 40)
'TOP = ../..\nSWIG = $(TOP)/.' 'TOP = ../..\nSWIG = $(TOP)/.'
&gt;&gt;&gt; example.read(f,40) &gt;&gt;&gt; example.read(f, 40)
'./swig\nSRCS = example.c\nTARGET ' './swig\nSRCS = example.c\nTARGET '
&gt;&gt;&gt; example.close(f) &gt;&gt;&gt; example.close(f)
0 0
&gt;&gt;&gt; g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644) &gt;&gt;&gt; g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644)
&gt;&gt;&gt; example.write(g,"Hello world\n") &gt;&gt;&gt; example.write(g, "Hello world\n")
12 12
&gt;&gt;&gt; example.write(g,"This is a test\n") &gt;&gt;&gt; example.write(g, "This is a test\n")
15 15
&gt;&gt;&gt; example.close(g) &gt;&gt;&gt; example.close(g)
0 0
@ -3959,7 +3959,7 @@ list. Consider:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(in, fragment="frag1,frag2,frag3") {...} %typemap(in, fragment="frag1, frag2, frag3") {...}
</pre> </pre>
</div> </div>
@ -4421,7 +4421,7 @@ You can access the functions in a normal way from the scripting interpreter:
# Python # Python
foo(3) # foo(int) foo(3) # foo(int)
foo(3.5) # foo(double) foo(3.5) # foo(double)
foo("hello",5) # foo(char *, int) foo("hello", 5) # foo(char *, int)
# Tcl # Tcl
foo 3 # foo(int) foo 3 # foo(int)
@ -4463,7 +4463,7 @@ _wrap_foo_2(argc, args[]) { // foo(char *, int)
... ...
arg1 = FromString(args[0]); arg1 = FromString(args[0]);
arg2 = FromInteger(args[1]); arg2 = FromInteger(args[1]);
result = foo(arg1,arg2); result = foo(arg1, arg2);
return ToInteger(result); return ToInteger(result);
} }
@ -4479,15 +4479,15 @@ Next, a dynamic dispatch function is generated:
_wrap_foo(argc, args[]) { _wrap_foo(argc, args[]) {
if (argc == 1) { if (argc == 1) {
if (IsInteger(args[0])) { if (IsInteger(args[0])) {
return _wrap_foo_0(argc,args); return _wrap_foo_0(argc, args);
} }
if (IsDouble(args[0])) { if (IsDouble(args[0])) {
return _wrap_foo_1(argc,args); return _wrap_foo_1(argc, args);
} }
} }
if (argc == 2) { if (argc == 2) {
if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) { if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) {
return _wrap_foo_2(argc,args); return _wrap_foo_2(argc, args);
} }
} }
error("No matching function!\n"); error("No matching function!\n");
@ -4568,7 +4568,7 @@ The following excerpt from the Python module illustrates this:
<div class="code"> <div class="code">
<pre> <pre>
/* Python type checking rules */ /* Python type checking rules */
/* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */ /* Note: %typecheck(X) is a macro for %typemap(typecheck, precedence=X) */
%typecheck(SWIG_TYPECHECK_INTEGER) %typecheck(SWIG_TYPECHECK_INTEGER)
int, short, long, int, short, long,
@ -4599,7 +4599,7 @@ The following excerpt from the Python module illustrates this:
$1 = PyString_Check($input) ? 1 : 0; $1 = PyString_Check($input) ? 1 : 0;
} }
%typemap(typecheck,precedence=SWIG_TYPECHECK_POINTER,noblock=1) SWIGTYPE * { %typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER, noblock=1) SWIGTYPE * {
void *vptr = 0; void *vptr = 0;
int res = SWIG_ConvertPtr($input, &amp;vptr, $1_descriptor, 0); int res = SWIG_ConvertPtr($input, &amp;vptr, $1_descriptor, 0);
$1 = SWIG_IsOK(res) ? 1 : 0; $1 = SWIG_IsOK(res) ? 1 : 0;
@ -4659,7 +4659,7 @@ If you write a typecheck typemap and omit the precedence level, for example comm
<div class="code"> <div class="code">
<pre> <pre>
%typemap(typecheck /*,precedence=SWIG_TYPECHECK_INTEGER*/) int { %typemap(typecheck /*, precedence=SWIG_TYPECHECK_INTEGER*/) int {
$1 = PyInt_Check($input) ? 1 : 0; $1 = PyInt_Check($input) ? 1 : 0;
} }
</pre> </pre>
@ -4711,7 +4711,7 @@ a set of typemaps like this:
<div class="code"> <div class="code">
<pre> <pre>
%typemap(in,numinputs=0) int *OUTPUT (int temp) { %typemap(in, numinputs=0) int *OUTPUT (int temp) {
$1 = &amp;temp; $1 = &amp;temp;
} }
%typemap(argout) int *OUTPUT { %typemap(argout) int *OUTPUT {
@ -4762,7 +4762,7 @@ For example:
%typemap(check) int *POSITIVE { %typemap(check) int *POSITIVE {
if (*$1 &lt;= 0) { if (*$1 &lt;= 0) {
SWIG_exception(SWIG_ValueError,"Expected a positive number!\n"); SWIG_exception(SWIG_ValueError, "Expected a positive number!\n");
return NULL; return NULL;
} }
} }

View file

@ -95,7 +95,7 @@ int execlp(const char *path, const char *arg1, ...);
... ...
/* Example */ /* Example */
execlp("ls","ls","-l",NULL); execlp("ls", "ls", "-l", NULL);
</pre> </pre>
</div> </div>
@ -189,9 +189,9 @@ In contrast, suppose you attempted to make some kind of wrapper around
<pre> <pre>
int wrap_printf(const char *fmt, ...) { int wrap_printf(const char *fmt, ...) {
va_list ap; va_list ap;
va_start(ap,fmt); va_start(ap, fmt);
... ...
printf(fmt,ap); printf(fmt, ap);
... ...
va_end(ap); va_end(ap);
}; };
@ -478,7 +478,7 @@ wrap_printf() {
arg1 = "%s"; arg1 = "%s";
arg2 = (void *) PyString_AsString(arg2obj); arg2 = (void *) PyString_AsString(arg2obj);
... ...
result = printf(arg1,arg2); result = printf(arg1, arg2);
... ...
} }
</pre> </pre>
@ -633,10 +633,10 @@ example. For example:
argc = PyTuple_Size(varargs); argc = PyTuple_Size(varargs);
argv = (char **) malloc(sizeof(char *)*(argc+1)); argv = (char **) malloc(sizeof(char *)*(argc+1));
for (i = 0; i &lt; argc; i++) { for (i = 0; i &lt; argc; i++) {
PyObject *o = PyTuple_GetItem(varargs,i); PyObject *o = PyTuple_GetItem(varargs, i);
if (!PyString_Check(o)) { if (!PyString_Check(o)) {
free(argv); free(argv);
PyErr_SetString(PyExc_ValueError,"Expected a string"); PyErr_SetString(PyExc_ValueError, "Expected a string");
SWIG_fail; SWIG_fail;
} }
argv[i] = PyString_AsString(o); argv[i] = PyString_AsString(o);
@ -733,7 +733,7 @@ As a more extreme example of libffi, here is some code that attempts to wrap <tt
argc = PyTuple_Size(varargs); argc = PyTuple_Size(varargs);
argv = (vtype *) malloc(argc*sizeof(vtype)); argv = (vtype *) malloc(argc*sizeof(vtype));
for (i = 0; i &lt; argc; i++) { for (i = 0; i &lt; argc; i++) {
PyObject *o = PyTuple_GetItem(varargs,i); PyObject *o = PyTuple_GetItem(varargs, i);
if (PyInt_Check(o)) { if (PyInt_Check(o)) {
argv[i].type = VT_INT; argv[i].type = VT_INT;
argv[i].val.ivalue = PyInt_AsLong(o); argv[i].val.ivalue = PyInt_AsLong(o);
@ -745,7 +745,7 @@ As a more extreme example of libffi, here is some code that attempts to wrap <tt
argv[i].val.pvalue = (void *) PyString_AsString(o); argv[i].val.pvalue = (void *) PyString_AsString(o);
} else { } else {
free(argv); free(argv);
PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); PyErr_SetString(PyExc_ValueError, "Unsupported argument type");
return NULL; return NULL;
} }
} }

View file

@ -68,7 +68,7 @@ First, you can run SWIG with the <tt>-w</tt> command line option. For example:
<div class="shell"> <div class="shell">
<pre> <pre>
% swig -python -w501 example.i % swig -python -w501 example.i
% swig -python -w501,505,401 example.i % swig -python -w501, 505, 401 example.i
</pre> </pre>
</div> </div>
@ -81,7 +81,7 @@ into the input file:
<pre> <pre>
%module example %module example
#pragma SWIG nowarn=501 #pragma SWIG nowarn=501
#pragma SWIG nowarn=501,505,401 #pragma SWIG nowarn=501, 505, 401
</pre> </pre>
</div> </div>
@ -170,7 +170,7 @@ previous section--simply add a "+" to all warning numbers. For example:
<div class="shell"> <div class="shell">
<pre> <pre>
% swig -w+309,+452 example.i % swig -w+309, +452 example.i
</pre> </pre>
</div> </div>
@ -180,7 +180,7 @@ or in your interface file use either
<div class="code"> <div class="code">
<pre> <pre>
#pragma SWIG nowarn=+309,+452 #pragma SWIG nowarn=+309, +452
</pre> </pre>
</div> </div>
@ -190,7 +190,7 @@ or
<div class="code"> <div class="code">
<pre> <pre>
%warnfilter(+309,+452) foo; %warnfilter(+309, +452) foo;
</pre> </pre>
</div> </div>
@ -205,12 +205,12 @@ You can of course also enable all warnings and suppress a select few, for exampl
<div class="shell"> <div class="shell">
<pre> <pre>
% swig -Wextra -w309,452 example.i % swig -Wextra -w309, 452 example.i
</pre> </pre>
</div> </div>
<p> <p>
The warnings on the right take precedence over the warnings on the left, so in the above example <tt>-Wextra</tt> adds numerous warnings including 452, but then <tt>-w309,452</tt> overrides this and so 452 is suppressesed. The warnings on the right take precedence over the warnings on the left, so in the above example <tt>-Wextra</tt> adds numerous warnings including 452, but then <tt>-w309, 452</tt> overrides this and so 452 is suppressesed.
</p> </p>
<p> <p>

View file

@ -86,7 +86,7 @@ Note: when creating a C++ extension, you must run SWIG with the <tt>-c++</tt> op
<h2>A sample Python script</h2> <h2>A sample Python script</h2>
Click <a href="example.py">here</a> to see a script that calls the C++ functions from Python. Click <a href="runme.py">here</a> to see a script that calls the C++ functions from Python.
<h2>Key points</h2> <h2>Key points</h2>

View file

@ -17,7 +17,7 @@ to see a SWIG interface with some constant declarations in it.
<h2>Accessing Constants from Python</h2> <h2>Accessing Constants from Python</h2>
Click <a href="example.py">here</a> to see a script that prints out the values Click <a href="runme.py">here</a> to see a script that prints out the values
of the constants contained in the above file. of the constants contained in the above file.
<h2>Key points</h2> <h2>Key points</h2>

View file

@ -19,7 +19,7 @@ of enumerated types are handled as integers.
<ul> <ul>
<li><a href="example.h">example.h</a>. Header file containing some enums. <li><a href="example.h">example.h</a>. Header file containing some enums.
<li><a href="example.i">example.i</a>. Interface file. <li><a href="example.i">example.i</a>. Interface file.
<li><a href="example.py">example.py</a>. Sample Python script. <li><a href="runme.py">runme.py</a>. Sample Python script.
</ul> </ul>
<h2>Notes</h2> <h2>Notes</h2>

View file

@ -65,7 +65,7 @@ Here are some files that illustrate this with a simple example:
<li><a href="example.c">example.c</a> <li><a href="example.c">example.c</a>
<li><a href="example.h">example.h</a> <li><a href="example.h">example.h</a>
<li><a href="example.i">example.i</a> (SWIG interface) <li><a href="example.i">example.i</a> (SWIG interface)
<li><a href="example.py">example.py</a> (Sample script) <li><a href="runme.py">runme.py</a> (Sample script)
</ul> </ul>
<h2>Notes</h2> <h2>Notes</h2>

View file

@ -145,7 +145,7 @@ extraction.
<ul> <ul>
<li> <a href="example.c">example.c</a> (C Source) <li> <a href="example.c">example.c</a> (C Source)
<li> <a href="example.i">example.i</a> (SWIG interface) <li> <a href="example.i">example.i</a> (SWIG interface)
<li> <a href="example.py">example.py</a> (Python Script) <li> <a href="runme.py">runme.py</a> (Python Script)
</ul> </ul>
<h2>Notes</h2> <h2>Notes</h2>

View file

@ -121,7 +121,7 @@ Click <a href="example.i">here</a> to see a SWIG interface file with these addit
<h2>Sample Python script</h2> <h2>Sample Python script</h2>
Click <a href="example.py">here</a> to see a script that manipulates some C++ references. Click <a href="runme.py">here</a> to see a script that manipulates some C++ references.
<h2>Notes:</h2> <h2>Notes:</h2>

View file

@ -65,7 +65,7 @@ to create the extension <tt>examplemodule.so</tt>.
<h2>Using the extension</h2> <h2>Using the extension</h2>
Click <a href="example.py">here</a> to see a script that calls our C functions from Python. Click <a href="runme.py">here</a> to see a script that calls our C functions from Python.
<h2>Key points</h2> <h2>Key points</h2>

View file

@ -48,7 +48,7 @@ double foo;
</blockquote> </blockquote>
it will be accessed in the Python module as <tt>cvar.foo</tt>. Click it will be accessed in the Python module as <tt>cvar.foo</tt>. Click
<a href="example.py">here</a> to see a script that updates and prints <a href="runme.py">here</a> to see a script that updates and prints
out the values of the variables using this technique. out the values of the variables using this technique.
<h2>Key points</h2> <h2>Key points</h2>