SWIG Myths
Here are some common misconceptions about SWIG that have occasionally
appeared on other web pages and in articles--especially those that
describe older SWIG versions.
Myth: SWIG only really works with ANSI C
C++ support in current SWIG releases is quite advanced--providing support for nearly
every C++ feature including templates, namespaces, operators, overloaded methods,
and more. The only major C++ feature not supported is nested classes---and we're
working on that. See the Features page for more information.
Myth: SWIG wraps C++ into this unusable
low-level "C-tran" interface.
class Foo {
public:
Foo();
Foo(const Foo &);
void spam(int x);
void spam(double x);
void spam(char *x, int n);
};
They can be used in a completely natural way from most SWIG language modules. For example,
in Python:
>>> f = Foo()
>>> f.spam(3)
>>> f.spam(3.5)
>>> f.spam("hello",5)
>>> g = Foo(f) # Make a copy
Or in Tcl:
The SWIG implementation of overloading utilizes type categories and a type precedence scheme that results in the generation of dynamic dispatch functions. The order in which declarations appear does not matter nor does SWIG rely on unreliable mechanisms like trial execution (i.e., trying methods one by one until one happens to execute successfully). Overloading support in SWIG is more advanced than that.% Foo f % f spam 3 % f spam 3.5 % f spam "hello" 5 % Foo g f
Due to the dynamic nature of scripting languages, it is not possible to fully disambiguate overloaded methods to the same degree as in C++. For example, you might have declarations like this:
In this case, SWIG provides a number of directives to either rename or ignore one of the declarations. For example:int foo(int); long foo(long);
or%ignore foo(long);
%rename(foo_long) foo(long);
In this case, "deque_int" becomes the target language name for the wrapped object. You would use it just like a normal class in the extension module:%template(deque_int) std::deque<int>;
On the subject of smart-pointers, those are supported too. For example, suppose you had some code like this:>>> d = deque_int(100) >>> d.size() 100 >>>
class Foo {
public:
int x;
int spam(int x);
};
template<class T> class SmartPtr {
public:
...
T *operator->();
...
};
typedef SmartPtr<Foo> FooPtr;
FooPtr make_Foo();
To wrap this with SWIG, just tell it about a template instantiation. For example:
Now, in the target language, the wrapper object works just like you would expect:%template(FooPtr) SmartPtr<Foo>;
>>> f = make_Foo() >>> f.x = 3 >>> f.spam(42)