### Install Node-API Addon Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command globally installs the `node-addon-api` package, which is required for running examples with the Node-API engine. ```bash $ sudo npm install -g node-addon-api ``` -------------------------------- ### SWIG Language Module check.list File Setup Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Instructions for setting up the check.list file for a new SWIG language module's examples directory, by copying and modifying an existing Python example. ```Shell cp ../python/check.list . ``` -------------------------------- ### Install JavascriptCore Development Library Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command installs the `libjavascriptcoregtk-1.0-dev` package, which is required to run examples with the JavascriptCore engine on Ubuntu-based systems. ```bash $ sudo apt-get install libjavascriptcoregtk-1.0-dev ``` -------------------------------- ### Install Node.js Development Library for V8 Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command installs the `libnode-dev` package, which provides the necessary libraries for running examples with the V8 engine. ```bash $ sudo apt-get install libnode-dev ``` -------------------------------- ### Manually Generating and Installing Go Wrappers with SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This snippet demonstrates the manual process of generating Go wrapper code using SWIG and then installing the resulting Go package. It involves running SWIG with the `-go` option on an interface file and subsequently using `go install` to compile and install the generated Go module. ```Shell % swig -go example.i % go install ``` -------------------------------- ### Example Output of Android NDK Build Process Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Android This snippet shows the typical console output when running `ndk-build` after configuring the `Android.mk`. It illustrates the compilation steps for C++ files, the creation of a static library, the linking of the shared library (`libexample.so`), and its final installation into the `libs/armeabi` directory, confirming a successful build. ```Shell $ ndk-build Compile++ thumb : example <= example_wrap.cpp Compile++ thumb : example <= example.cpp StaticLibrary : libstdc++.a SharedLibrary : libexample.so Install : libexample.so => libs/armeabi/libexample.so ``` -------------------------------- ### Concrete Examples of Individual Testcase Commands Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides specific examples of cleaning and running individual C, C++, and multi-module C++ test cases using their actual names. ```Shell make -s ret_by_value.clean make -s ret_by_value.ctest make -s bools.cpptest make -s imports.multicpptest ``` -------------------------------- ### CMake Configuration for SWIG Python Module Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Introduction This CMake script demonstrates the setup required to use SWIG for generating Python bindings. It locates SWIG and Python libraries, configures include paths, sets properties for the SWIG interface file (example.i) to enable C++ processing and include all definitions, and finally uses SWIG_ADD_MODULE to create a Python module named 'example' from the interface and C++ source files. ```CMake FIND_PACKAGE(SWIG REQUIRED) INCLUDE(${SWIG_USE_FILE}) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) SET(CMAKE_SWIG_FLAGS "") SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON) SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall") SWIG_ADD_MODULE(example python example.i example.cxx) SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) ``` -------------------------------- ### Real Examples of Individual Testcase Commands Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Extending Concrete examples demonstrating how to clean, run C, C++, and multi-module C++ individual testcases using specific testcase names. ```Shell make -s ret_by_value.clean make -s ret_by_value.ctest make -s bools.cpptest make -s imports.multicpptest ``` -------------------------------- ### Install CMake-win64 via Nuget for Windows Build Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Commands to install the CMake-win64 Nuget package, providing CMake for building SWIG on Windows. Includes both standard command prompt and PowerShell syntax. ```Batch C:\Tools\nuget install CMake-win64 -Version 3.15.5 -OutputDirectory C:\Tools\CMake ``` ```PowerShell & "C:\Tools\nuget" install CMake-win64 -Version 3.15.5 -OutputDirectory C:\Tools\CMake ``` -------------------------------- ### CMake Configuration for SWIG Python Module Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This CMake example demonstrates how to configure a project to use SWIG to create a Python wrapper for a C++ interface file (example.i). It finds SWIG and Python libraries, includes necessary directories, sets SWIG properties for example.i (C++ and includeall flag), adds a SWIG module named 'example' for Python, and links it against Python libraries. This setup generates native build files (makefiles, Visual Studio projects) that invoke SWIG to compile C++ files into a Python extension module (_example.so or _example.pyd). This allows easy cross-platform SWIG development. ```CMake # This is a CMake example for Python FIND_PACKAGE(SWIG REQUIRED) INCLUDE(${SWIG_USE_FILE}) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) SET(CMAKE_SWIG_FLAGS "") SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON) SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall") SWIG_ADD_MODULE(example python example.i example.cxx) SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) ``` -------------------------------- ### Build and Install SWIG on Unix Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Instructions to compile and install SWIG from a distributed tarball on Unix-like systems using GNU make. This assumes PCRE2 is installed and pcre2-config is available. ```Shell $ ./configure $ make $ make install ``` -------------------------------- ### Install Node-GYP Build Tool Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command globally installs `node-gyp`, a cross-platform command-line tool for compiling native Node.js addon modules. It is essential for building C++ extensions for Node.js. ```bash $ sudo npm install -g node-gyp ``` -------------------------------- ### Install Bison via Nuget for Windows Build Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Command to install the Bison Nuget package, a parser generator essential for compiling SWIG on Windows. ```Batch C:\Tools\nuget install Bison -Version 3.7.4 -OutputDirectory C:\Tools\bison ``` -------------------------------- ### C++ Uniform Initialization Examples Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This C++ snippet provides examples of uniform initialization using curly braces `{}`. It demonstrates direct member initialization for structs and constructor calls for classes, showcasing how this C++11 feature works. ```C++ struct BasicStruct { int x; double y; }; struct AltStruct { AltStruct(int x, double y) : x_{x}, y_{y} {} int x_; double y_; }; BasicStruct var1{5, 3.2}; // only fills the struct components AltStruct var2{2, 4.3}; // calls the constructor ``` -------------------------------- ### Run SWIG Javascript Examples Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command executes the SWIG Javascript examples using the specified engine. The `ENGINE` variable can be set to `node`, `jsc`, `v8`, or `napi` to select the desired Javascript runtime. ```bash $ make check-javascript-examples ENGINE=jsc ``` -------------------------------- ### Install Bison using Nuget Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Windows Command to install the Bison package via Nuget, specifying version and output directory for building SWIG. ```Shell C:\Tools\nuget install Bison -Version 3.7.4 -OutputDirectory C:\Tools\bison ``` -------------------------------- ### Building Ruby Extension Module with mkmf Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation After creating extconf.rb, these commands are used to build and install the Ruby extension module. extconf.rb generates the Makefile, make compiles, and make install installs the module. ```Bash $ ruby extconf.rb $ make $ make install ``` -------------------------------- ### Java Director Method Override and Main Class Setup Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This Java code defines a 'DerivedClass' that extends 'MyClass' and overrides the 'dirmethod' to throw different Java exceptions based on the input 'x'. It also includes the 'runme' class, which serves as the entry point for the application, loading the native library and preparing for the execution of the examples. ```Java class DerivedClass extends MyClass { @Override public void dirmethod(int x) { if (x < 0) throw new IndexOutOfBoundsException("Index is negative"); else if (x == 0) throw new MyException("MyException: bad dirmethod"); } } public class runme { public static void main(String argv[]) { System.loadLibrary("example"); ... code snippets shown below ... } } ``` -------------------------------- ### Configure SWIG Python Extension with distutils setup.py Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This Python script defines the configuration for building a SWIG-generated Python extension module using distutils. It specifies the extension name (_example), the source files (example_wrap.c, example.c), and package metadata for the setup function. ```Python #!/usr/bin/env python3 """ setup.py file for SWIG example """ from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.c'], ) setup (name = 'example', version = '0.1', author = "SWIG Docs", description = """Simple swig example from docs""", ext_modules = [example_module], py_modules = ["example"], ) ``` -------------------------------- ### Bootstrap Node-API Project with Yeoman Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These commands outline the process of setting up a Node-API project using Yeoman. It involves installing Yeoman and the Node-API module generator, creating a project directory, generating a skeleton, updating `node-addon-api`, generating SWIG wrappers, and finally configuring and building the module with `node-gyp`. ```bash $ sudo npm install -g yo $ sudo npm install -g generator-napi-module $ mkdir example $ cd example $ yo napi-module $ npm install node-addon-api@latest $ swig -javascript -napi -c++ -o src/example.cc example.i $ node-gyp configure $ node-gyp build ``` -------------------------------- ### SWIG: Example of Missing shared_ptr Macros in Hierarchy Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Library Provides an example of a SWIG interface file where `%shared_ptr` macros are omitted for some classes in an inheritance hierarchy (`GrandParent`, `Child`). This setup is used to demonstrate the warnings SWIG generates in such cases. ```SWIG %include "boost_shared_ptr.i" %shared_ptr(Parent); %inline %{ #include struct GrandParent { virtual ~GrandParent() {} }; struct Parent : GrandParent { virtual ~Parent() {} }; struct Child : Parent { virtual ~Child() {} }; %} ``` -------------------------------- ### C# Usage of SWIG-Wrapped CDate Property Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Demonstrates how to set and get the SWIG-wrapped C++ CDate variable as a System.DateTime property in C#. The module name is 'example'. ```C# example.ImportantDate = new System.DateTime(2000, 11, 22); System.DateTime importantDate = example.ImportantDate; Console.WriteLine("Important date: " + importantDate); ``` -------------------------------- ### Example Usage of SWIG char** Typemap in Tcl Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Demonstrates how to call the `print_args` function from Tcl, passing a Tcl list that gets converted to a C `char **` by the SWIG typemap. ```Tcl % print_args {John Guido Larry} argv[0] = John argv[1] = Guido argv[2] = Larry 3 ``` -------------------------------- ### Perl Example: Accessing SWIG Wrapped C Struct Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Demonstrates how to use the SWIG-generated Perl functions to create an instance of `Vector`, get its `x` component, and set its `x` component. ```Perl $v = example::new_Vector(); print example::Vector_x_get($v), "\n"; # Get x component example::Vector_x_set($v, 7.8); # Change x component ``` -------------------------------- ### SWIG C++ Wrapper Compilation Steps Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides a step-by-step command-line example for generating and compiling a SWIG C++ wrapper. It demonstrates using `swig -c++` to create the wrapper file and then compiling it with a C++ compiler to produce a shared library. ```Shell $ swig -c++ -tcl example.i $ c++ -fPIC -c example_wrap.cxx $ c++ example_wrap.o $(OBJS) -o example.so ``` -------------------------------- ### Configure TCL Environment Variables for SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Windows This snippet provides the necessary environment variables, TCL_INCLUDE and TCL_LIB, for integrating TCL with SWIG. It includes an example path for an ActiveTcl 8.6 installation. ```TCL TCL_INCLUDE: C:\ActiveTcl\include TCL_LIB: C:\ActiveTcl\lib\tcl86t.lib ``` -------------------------------- ### Generate PHP Extension Wrapper Files with SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command demonstrates how to use SWIG with the `-php` option to generate the necessary C wrapper code (`example_wrap.c`) and PHP header file (`php_example.h`) from a SWIG interface file (`example.i`). It's the first step in creating a PHP extension. ```Bash swig -php example.i ``` -------------------------------- ### Load SWIG Java Module with System.loadLibrary Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Illustrates a Java class (runme.java) demonstrating how to load a native shared library named 'example' using System.loadLibrary within a static initializer block. It then shows an example of calling a native method example.fact from the loaded module. ```Java // runme.java public class runme { static { System.loadLibrary("example"); } public static void main(String argv[]) { System.out.println(example.fact(4)); } } ``` -------------------------------- ### Perl Example: Using SWIG Wrapped C++ Class Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Demonstrates how to use the SWIG-generated Perl functions to interact with a `List` C++ object, including creating, inserting elements, printing, and getting its length. ```Perl use example; $l = example::new_List(); example::List_insert($l, "Ale"); example::List_insert($l, "Stout"); example::List_insert($l, "Lager") example::List_print($l) Lager Stout Ale print example::List_length_get($l), "\n"; 3 ``` -------------------------------- ### Install Node.js on Ubuntu via PPA Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These commands add the Node.js PPA to your system, update the package list, and then install Node.js. This method provides a more up-to-date version of Node.js compared to default distribution packages. ```bash $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update $ sudo apt-get install nodejs ``` -------------------------------- ### C++ Namespace Name Conflict Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Shows a scenario where two different C++ namespaces define functions with the same name but different signatures. This setup leads to a name conflict when SWIG flattens namespaces, resulting in an error. ```C++ namespace A { void foo(int); } namespace B { void foo(double); } ``` -------------------------------- ### Building C Shared Libraries on Solaris and Linux Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides shell commands for compiling and linking C source files (example.c, example_wrap.c) into a dynamically loadable shared library (.so) on Solaris using `gcc` and `ld`, and on Linux using `gcc`. ```Shell # Build a shared library for Solaris gcc -fPIC -c example.c example_wrap.c -I/usr/local/include ld -G example.o example_wrap.o -o example.so # Build a shared library for Linux gcc -fPIC -c example.c example_wrap.c -I/usr/local/include gcc -shared example.o example_wrap.o -o example.so ``` -------------------------------- ### Node-GYP Configuration File (binding.gyp) Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This `binding.gyp` file, in JSON format, configures `node-gyp` to build a native Node.js module named 'example'. It specifies the C++ source files required for compilation, including the SWIG-generated wrapper. ```json { "targets": [ { "target_name": "example", "sources": [ "example.cxx", "example_wrap.cxx" ] } ] } ``` -------------------------------- ### Configure Python Environment Variables for SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Windows This snippet provides the necessary environment variables, PYTHON_INCLUDE and PYTHON_LIB, for integrating Python with SWIG. It includes an example path for a Python 3.13 installation within a Conda environment. ```Python PYTHON_INCLUDE: C:\miniconda3\envs\python\include PYTHON_LIB: C:\miniconda3\envs\python\libs\python313.lib ``` -------------------------------- ### Define Android NDK Build System (Android.mk) Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This `Android.mk` file defines the build system for the Android NDK. It specifies the module name 'example' and lists the source files (`example_wrap.c`, `example.c`) required to build a shared library (`libexample.so`). ```Makefile # File: Android.mk LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := example LOCAL_SRC_FILES := example_wrap.c example.c include $(BUILD_SHARED_LIBRARY) ``` -------------------------------- ### List Available Android Target IDs Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command lists all available Android target IDs installed with the SDK. It is used to verify and select the correct target ID for building Android applications, which might need adjustment based on the development setup. ```Bash android list targets ``` -------------------------------- ### Example C Header File for SWIG Wrapping Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIG Presents a simple C header file (`header.h`) containing function declarations. This file serves as an example of the C source code that would typically be wrapped by SWIG. ```C /* File : header.h */ #include #include extern int foo(double); extern double bar(int, int); extern void dump(FILE *f); ``` -------------------------------- ### Define a C++ Class for SWIG Wrapping Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Defines a basic C++ class `List` with a constructor, destructor, methods for searching, inserting, removing, getting elements, and a public data member `length`. This class serves as an example for SWIG's class wrapping. ```C++ class List { public: List(); ~List(); int search(char *item); void insert(char *item); void remove(char *item); char *get(int n); int length; }; ``` -------------------------------- ### Basic SWIG Command Line Usage Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIG Demonstrates the fundamental command structure for running SWIG, specifying options and the input interface or header file. It also notes how to access the full help documentation. ```bash swig [ options ] filename ``` -------------------------------- ### Integrate Native Extension with WebKit on GTK Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This C code illustrates the integration of a native extension, 'example', into a GTK application using WebKit. It outlines the initialization of GTK and WebKit, obtaining the JavaScript global context, and exposing the native extension's JSObjectRef to JavaScript. The snippet also includes loading a URI into the WebView. ```C #include #include extern bool example_initialize(JSGlobalContextRef context); int main(int argc, char* argv[]) { // Initialize GTK+ gtk_init(&argc, &argv); ... // Create a browser instance WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); WebFrame *webframe = webkit_web_view_get_main_frame(webView); JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); JSObjectRef global = JSContextGetGlobalObject(context); JSObjectRef exampleModule; example_initialize(context, &exampleModule); JSStringRef jsName = JSStringCreateWithUTF8CString("example"); JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL); JSStringRelease(jsName); ... // Load a web page into the browser instance webkit_web_view_load_uri(webView, "https://www.webkitgtk.org/"); ... // Run the main GTK+ event loop gtk_main(); return 0; } ``` -------------------------------- ### C++ Example: Setting and Getting Element in Container Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Illustrates the straightforward usage of the `Container` and `Element` classes in C++. An `Element` object is created on the stack, its address is passed to `Container::setElement`, and its value is retrieved, demonstrating the expected behavior where the `Element` remains valid. ```C++ Container container; Element element(20); container.setElement(&element); cout << "element.value: " << container.getElement()->value << endl; ``` -------------------------------- ### C++ Classes and Functions for Multiple Inheritance Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Defines three C++ classes (A, B, C) where C inherits from both A and B, along with functions that accept pointers to A and B. This setup is used to demonstrate issues with type information loss when casting pointers. ```C++ class A { public: int x; }; class B { public: int y; }; class C : public A, public B { }; int A_function(A *a) { return a->x; } int B_function(B *b) { return b->y; } ``` -------------------------------- ### SWIG Typemap Definition Examples Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides various examples of SWIG typemap definitions, demonstrating simple declarations, use with extra argument names, multiple types, modifiers, multi-argument patterns, and extra pattern parameters. ```SWIG /* Simple typemap declarations */ %typemap(in) int { $1 = PyInt_AsLong($input); } %typemap(in) int "$1 = PyInt_AsLong($input);" %typemap(in) int %{ $1 = PyInt_AsLong($input); %} /* Typemap with extra argument name */ %typemap(in) int nonnegative { ... } /* Multiple types in one typemap */ %typemap(in) int, short, long { $1 = SvIV($input); } /* Typemap with modifiers */ %typemap(in, doc="integer") int "$1 = scm_to_int($input);" /* Typemap applied to patterns of multiple arguments */ %typemap(in) (char *str, int len), (char *buffer, int size) { $1 = PyString_AsString($input); $2 = PyString_Size($input); } /* Typemap with extra pattern parameters */ %typemap(in, numinputs=0) int *output (int temp), long *output (long temp) { $1 = &temp; } ``` -------------------------------- ### Configure SWIG TCL Environment Variables Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This snippet demonstrates how to set the TCL_INCLUDE and TCL_LIB environment variables for SWIG when using TCL. These variables point to the TCL header files and library required for linking. The example shows a setup for ActiveTcl 8.6 on Windows. ```TCL TCL_INCLUDE: C:\ActiveTcl\include TCL_LIB: C:\ActiveTcl\lib\tcl86t.lib ``` -------------------------------- ### Create and Build Android Project Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Commands to initialize a new Android project named 'SwigSimple' and build it using Ant. This sets up the basic application structure for the Android app. ```Shell $ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple $ cd simple $ ant debug ``` -------------------------------- ### SWIG Interface: Wrapping C Array with %array_functions Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Library Example of a SWIG interface file (`.i`) demonstrating how to use the `%array_functions` macro from `carrays.i` to wrap a C function that takes a double array. This setup allows scripting languages to interact with the C array. ```SWIG %module example %include "carrays.i" %array_functions(double, doubleArray); void print_array(double x[10]); ``` -------------------------------- ### Compile SWIG OCaml Bindings for Qt Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This bash script outlines the steps to compile the SWIG-generated OCaml bindings for the Qt example. It involves running SWIG to generate OCaml and C++ wrapper files, compiling OCaml source files, compiling the C++ wrapper, and finally linking everything into an OCaml toplevel executable. ```Bash $ QTPATH=/your/qt/path $ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done $ ocamlc -c swig.mli ; ocamlc -c swig.ml $ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml $ swig -ocaml -c++ -o qt_wrap.c qt.i $ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c $ ocamlc -c qt.mli $ ocamlc -c qt.ml $ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \ -L$QTPATH/lib -cclib -lqt ``` -------------------------------- ### SWIG Generated C Accessor Functions for Nested Unions Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides examples of the C accessor functions that SWIG generates to allow scripting languages to interact with members of nested structures and unions. These functions provide a low-level interface for getting and setting values within the transformed structure. ```C Object_intRep *Object_intRep_get(Object *o) { return (Object_intRep *) &o->intRep; } int Object_intRep_ivalue_get(Object_intRep *o) { return o->ivalue; } int Object_intRep_ivalue_set(Object_intRep *o, int value) { return (o->ivalue = value); } double Object_intRep_dvalue_get(Object_intRep *o) { return o->dvalue; } ... etc ... ``` -------------------------------- ### SWIG %define Macro for Array Helper Generation Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Preprocessor Illustrates the SWIG-specific %define directive for creating large, multi-line macros. This example defines an ARRAYHELPER macro that generates C functions for creating, deleting, getting, and setting elements in arrays of a specified type, then shows its usage for int and double arrays. ```SWIG %define ARRAYHELPER(type, name) %inline %{ type *new_ ## name (int nitems) { return (type *) malloc(sizeof(type)*nitems); } void delete_ ## name(type *t) { free(t); } type name ## _get(type *t, int index) { return t[index]; } void name ## _set(type *t, int index, type val) { t[index] = val; } %} %enddef ARRAYHELPER(int, IntArray) ARRAYHELPER(double, DoubleArray) ``` -------------------------------- ### Compile SWIG Lua Wrapper and Module (Bash) Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This snippet provides the Bash commands to compile a SWIG-generated Lua wrapper and link it with a C example file to create a dynamically loadable Lua module (.so file). It assumes example.i is the SWIG interface file and example.c is the C source. ```Bash swig -lua example.i -o example_wrap.c gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o gcc -fPIC -c example.c -o example.o gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so ``` -------------------------------- ### Adding Python Code at File Beginning with %pythonbegin Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This example illustrates the use of the %pythonbegin directive to insert Python code at the very start of the generated .py file. This is useful for adding module-level comments, 'from __future__ import' statements, or other Python imports that must appear at the top of the file. ```SWIG %pythonbegin %{ # This module provides wrappers to the Whizz Bang library %} %pythonbegin %{ from __future__ import print_function print("Loading", "Whizz", "Bang", sep=' ... ') %} ``` -------------------------------- ### SWIG Interface File Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation A basic SWIG interface file (`example.i`) demonstrating module definition and C function declaration for wrapping. ```C /* File: example.i */ %module test %{ #include "stuff.h" %} int fact(int n); ``` -------------------------------- ### SWIG Interface: Wrapping C Array with %array_class Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Library Example of a SWIG interface file (`.i`) demonstrating how to use the `%array_class` macro from `carrays.i` to wrap a C function that takes a double array. This setup allows scripting languages to interact with the C array using a class-based interface. ```SWIG %module example %include "carrays.i" %array_class(double, doubleArray); void print_array(double x[10]); ``` -------------------------------- ### Configure SWIG Python Environment Variables Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This snippet demonstrates how to set the PYTHON_INCLUDE and PYTHON_LIB environment variables for SWIG when using Python. These variables point to the Python header files and library required for linking, respectively. The example shows a setup for Python 3.13 within a Conda environment on Windows. ```Python PYTHON_INCLUDE: C:\miniconda3\envs\python\include PYTHON_LIB: C:\miniconda3\envs\python\libs\python313.lib ``` -------------------------------- ### Display SWIG Configure Script Help Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Command to display the available options and help information for the SWIG configure script, useful for understanding advanced configuration possibilities. ```Shell $ ./configure --help. ``` -------------------------------- ### Create SWIG Interface File for C++ Classes Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Android This SWIG interface file ('example.i') defines the SWIG module 'example' and includes the C++ header file 'example.h'. This setup instructs SWIG on how to generate wrapper code, making the C++ classes accessible from target languages like Java. ```SWIG /* File : example.i */ %module example %{ #include "example.h" %} /* Let's just grab the original header file here */ %include "example.h" ``` -------------------------------- ### Scilab Examples for Matrix Operations Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These Scilab commands illustrate how to interact with the C matrix manipulation functions ('create_matrix', 'get_matrix', 'set_matrix', 'print_matrix') exposed via SWIG, demonstrating matrix creation, printing, and element access/modification. ```Scilab --> m = create_matrix(); --> print_matrix(m); 1. 2. 3. 4. --> set_matrix(m, 1, 1, 5.); --> get_matrix(m, 1, 1) ans = 5. ``` -------------------------------- ### SWIG Interface Example Using cmalloc.i Macros Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation A SWIG interface example demonstrating the use of `%malloc`, `%free`, and `%allocators` macros from the `cmalloc.i` module. It creates wrappers for `int` and `double` types, including a pointer to int (`int *`). ```SWIG // SWIG interface %module example %include "cmalloc.i" %malloc(int); %free(int); %malloc(int *, intp); %free(int *, intp); %allocators(double); ``` -------------------------------- ### Create and Build Android Project Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Android Commands to initialize a new Android project named 'SwigSimple' and build it using the `android` and `ant` command-line tools. This sets up the basic project structure. ```bash $ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple $ cd simple $ ant debug ``` -------------------------------- ### Manipulate Pointers with SWIG Utility Functions in Scilab Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This Scilab example illustrates the use of SWIG's utility functions `SWIG_this()` to get a pointer's address and `SWIG_ptr()` to create a pointer from an address. It shows how a pointer created by `SWIG_ptr()` loses its specific type and becomes a generic 'pointer' type. ```Scilab --> f = fopen("junk", "w"); --> fputs("Hello", f); --> addr = SWIG_this(f) ans = 8219088. --> p = SWIG_ptr(addr); --> typeof(p) ans = pointer --> fputs(" World", p); --> fclose(f); ``` -------------------------------- ### Define a C++ Class for SWIG Wrapping Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This C++ code defines a `List` class with a constructor, destructor, various public methods for list manipulation (search, insert, remove, get), and a public `length` data member. This class serves as an example for SWIG's C++ class wrapping capabilities. ```C++ class List { public: List(); ~List(); int search(char *item); void insert(char *item); void remove(char *item); char *get(int n); int length; }; ``` -------------------------------- ### SWIG I/O Example: Printing to String and File Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Illustrates common usage of SWIG's internal I/O functions, demonstrating how to create a new string, print formatted output to it, and then print the string's content to a file. ```C /* Print into a string */ String *s = NewString(""); Printf(s, "Hello\n"); for (i = 0; i < 10; i++) { Printf(s, "%d\n", i); } ... /* Print string into a file */ Printf(f, "%s\n", s); ``` -------------------------------- ### Embed Lua Code in SWIG Module Initialization Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Demonstrates how to embed custom Lua code within a SWIG module using the %luacode directive. This code executes after module initialization, allowing for the definition of module-specific functions or other setup tasks. It shows how to define a 'greet' function within the 'example' module. ```SWIG %module example; %luacode { function example.greet() print "hello world" end print "Module loaded ok" } ... %} ``` -------------------------------- ### Configure Java Environment Variables for SWIG Examples on Windows Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Instructions for setting the necessary environment variables (JAVA_INCLUDE and JAVA_BIN) required to compile and run SWIG-generated Java examples using Visual C++ on Windows. These variables point to the Java Development Kit (JDK) include and binary directories, essential for the build process. ```APIDOC JAVA_INCLUDE: Set this to the directory containing jni.h JAVA_BIN: Set this to the bin directory containing javac.exe Example using the openjdk package installed in a Conda environment: JAVA_INCLUDE: C:\miniconda3\envs\java\Library\lib\jvm\include JAVA_BIN: C:\miniconda3\envs\java\Library\lib\jvm\bin ``` -------------------------------- ### C++ Classes for Stale Pointer Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Java Defines simple C++ classes `Obj` and `Node` where `Node` holds a pointer to `Obj`. This setup is used to illustrate a common memory management pitfall where Java's garbage collection can lead to a stale C++ pointer if ownership is not correctly managed. ```C++ class Obj {}; class Node { Obj *value; public: void set_value(Obj *v) { value = v; } }; ``` -------------------------------- ### Build PHP Dynamically Loadable Extension using GCC Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These GCC commands illustrate how to compile the SWIG-generated C wrapper (`example_wrap.c`) and your custom C source file (`example.c`) into object files, and then link them together to create a dynamically loadable PHP extension (`example.so`). The `php-config --includes` command provides necessary include paths, and `-fPIC` ensures position-independent code for shared libraries. ```Bash gcc `php-config --includes` -fPIC -c example_wrap.c example.c gcc -shared example_wrap.o example.o -o example.so ``` -------------------------------- ### SWIG Renaming Rules with %rename Directive Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIG Demonstrates various regular expression-based renaming rules in SWIG using the %rename directive. Examples include removing 'wx' prefixes from identifiers (except 'wxEVT'), simplifying enum item names by removing common prefixes, and stripping 'Set' or 'Get' prefixes from method names. ```SWIG %rename("%(regex:/wx(?!EVT)(.*)/\\1/)s") ""; // wxSomeWidget -> SomeWidget // wxEVT_PAINT -> wxEVT_PAINT // Apply a rule for renaming the enum elements to avoid the common prefixes // which are redundant in C#/Java %rename("%(regex:/^([A-Z][a-z]+)+_(.*)/\\2/)s", %$isenumitem) ""; // Colour_Red -> Red // Remove all "Set/Get" prefixes. %rename("%(regex:/^(Set|Get)(.*)/\\2/)s") ""; // SetValue -> Value // GetValue -> Value ``` -------------------------------- ### Node-GYP Configuration for SWIG Extension Build Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Specifies the `binding.gyp` file used by `node-gyp` to build the Node.js extension. It lists the source files (`example.cxx`, `example_wrap.cxx`) required for compilation. ```JSON { "targets": [ { "target_name": "example", "sources": [ "example.cxx", "example_wrap.cxx" ] } ] } ``` -------------------------------- ### Create SWIG Interface File for C Code Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Android SWIG interface file `example.i` that defines the module 'example' and declares the `gcd` function and `Foo` global variable from `example.c`. This file instructs SWIG on how to generate wrappers for the C code. ```swig /* File : example.i */ %module example %inline %{ extern int gcd(int x, int y); extern double Foo; %} ``` -------------------------------- ### SWIG Configuration for Python Modules in Same Package Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Configure SWIG to generate Python modules (foo.py and _foo.so) that are located within the same Python package. This setup leverages Python's __package__ or __name__ attributes for module loading. The example shows the SWIG directive, typical file structure, and the Python import statement. ```SWIG %module(package="mypackage") foo ``` ```File System /dir/mypackage/foo.py /dir/mypackage/__init__.py /dir/mypackage/_foo.so ``` ```Python from mypackage import foo ``` -------------------------------- ### Compiling SWIG Module with External Library (Initial Attempt) Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Command to compile a SWIG-generated wrapper (`example_wrap.o`) and application code (`example.o`) into a shared library (`example.so`), linking against an external library (`libfoo`). This setup can lead to runtime library loading issues if `libfoo.so` is not found by the dynamic linker. ```GCC $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ -o example.so ``` -------------------------------- ### Generate Lua Wrappers with SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command demonstrates how to run SWIG with the -lua option to generate C/C++ wrapper files (example_wrap.c or example_wrap.cxx) suitable for creating a Lua extension module. The generated file contains low-level wrappers that need to be compiled and linked. ```Shell $ swig -lua example.i ``` -------------------------------- ### SWIG: Catching Director Exceptions for Round-Trip Calls Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Provides an example of combining a normal %exception directive with the director exception handler. This setup allows C++ to catch Swig::DirectorException, ensuring that exceptions occurring in Perl during a round-trip method call (Perl -> C++ -> Perl) are properly propagated back to the original Perl caller. ```SWIG %exception { try { $action } catch (Swig::DirectorException &e) { SWIG_fail; } } ``` -------------------------------- ### Create SWIG Interface File for C++ (example.i) Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation Defines the SWIG module 'example' and includes the 'example.h' header, instructing SWIG to parse the C++ class definitions and generate wrapper code for target languages like Java. ```SWIG /* File : example.i */ %module example %{ #include "example.h" %} /* Let's just grab the original header file here */ %include "example.h" ``` -------------------------------- ### SWIG Wrapped C Declarations: Example Usage in Scripting Languages Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These code examples demonstrate how to access and use the C functions, variables, and constants wrapped by SWIG in different scripting languages. The Tcl example shows direct function calls and variable access, while the Python example uses the 'example' module and 'cvar' attribute for variables. ```Tcl % sin 3 5.2335956 % strcmp Dave Mike -1 % puts $Foo 42 % puts $STATUS 50 % puts $VERSION 1.1 ``` ```Python >>> example.sin(3) 5.2335956 >>> example.strcmp('Dave', 'Mike') -1 >>> print example.cvar.Foo 42 >>> print example.STATUS 50 >>> print example.VERSION 1.1 ``` -------------------------------- ### SWIG Generated Perl Proxy Class for C++ Vector Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This Perl code demonstrates the proxy class 'example::Vector' generated by SWIG. It encapsulates the low-level C accessor functions into object-oriented methods like 'new', 'DESTROY', 'FETCH' (for getting members), and 'STORE' (for setting members), providing a more idiomatic Perl interface to the C++ structure. ```Perl package example::Vector; @ISA = qw( example ); %OWNER = (); %BLESSEDMEMBERS = (); sub new () { my $self = shift; my @args = @_; $self = vectorc::new_Vector(@args); return undef if (!defined($self)); bless $self, "example::Vector"; $OWNER{$self} = 1; my %retval; tie %retval, "example::Vector", $self; return bless \%retval, "Vector"; } sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); delete $ITERATORS{$self}; if (exists $OWNER{$self}) { examplec::delete_Vector($self)); delete $OWNER{$self}; } } sub FETCH { my ($self, $field) = @_; my $member_func = "vectorc::Vector_${field}_get"; my $val = &$member_func($self); if (exists $BLESSEDMEMBERS{$field}) { return undef if (!defined($val)); my %retval; tie %retval, $BLESSEDMEMBERS{$field}, $val; return bless \%retval, $BLESSEDMEMBERS{$field}; } return $val; } sub STORE { my ($self, $field, $newval) = @_; my $member_func = "vectorc::Vector_${field}_set"; if (exists $BLESSEDMEMBERS{$field}) { &$member_func($self, tied(%{$newval})); } else { &$member_func($self, $newval); } } ``` -------------------------------- ### Build SWIG Python Extension using distutils Commands Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation These shell commands demonstrate how to compile a SWIG interface file (example.i) and then build the Python extension module using the setup.py script with distutils. The --inplace flag ensures the compiled module is placed in the current directory. ```Shell $ swig -python example.i $ python setup.py build_ext --inplace ``` -------------------------------- ### SWIG Support for std::result_of and Function Callbacks Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This snippet details the process of wrapping C++ code that uses `std::result_of` to determine function return types, enabling generic function calls. It includes the C++ and SWIG setup for specializing `std::result_of` and wrapping a generic test function, followed by a Python example demonstrating its usage with a callback. ```C++/SWIG %inline %{ #include typedef double(*fn_ptr)(double); %} namespace std { // Forward declaration of result_of template struct result_of; // Add in a partial specialization of result_of template<> struct result_of< fn_ptr(double) > { typedef double type; }; } %template() std::result_of< fn_ptr(double) >; %inline %{ double square(double x) { return (x * x); } template typename std::result_of::type test_result_impl(Fun fun, Arg arg) { return fun(arg); } %} %template(test_result) test_result_impl< fn_ptr, double >; %constant double (*SQUARE)(double) = square; ``` ```Python >>> test_result(SQUARE, 5.0) 25.0 ``` -------------------------------- ### SWIG MzScheme Module Build and Test Session on OS X Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation A comprehensive sequence of shell commands demonstrating the full workflow to compile the C code, generate SWIG wrappers, link the library, and test the module within an MzScheme interactive session on an OS X machine. It highlights steps for 32-bit compilation and proper library placement for MzScheme to load the extension. ```Shell % swig -mzscheme -declaremodule example.i % gcc -c -m32 -o example.o example.c # force 32-bit object file (mzscheme is 32-bit only) % libtool -dynamic -o libexample.dylib example.o # make it into a library % ls # what've we got so far? example.c example.o example.h example_wrap.c example.i libexample.dylib* % mzc --cgc --cc example_wrap.c # compile the wrapping code % LDFLAGS="-L. -lexample" mzc --ld example_wrap.dylib example_wrap.o # ...and link it % mzscheme -e '(path->string (build-path \"compiled\" \"native\" (system-library-subpath)))' "compiled/native/i386-macosx/3m" % mkdir -p compiled/native/i386-macosx/3m # move the extension library to a magic place % mv example_wrap.dylib compiled/native/i386-macosx/3m/example_ss.dylib % mzscheme Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc. > (require "example.ss") > (fact 5) 120 > ^D % echo 'It works!' ``` -------------------------------- ### SWIG Typemap and C++ Class Definition for Return Value Example Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/Typemaps Defines a SWIG 'out' typemap and an inline C++ struct XX with constructors, assignment operator, and a static 'create' method. This setup is used to demonstrate object lifecycle during return by value, serving as the base code for illustrating SWIG's default behavior versus behavior with the 'optimal' attribute. ```SWIG/C++ %typemap(out) SWIGTYPE %{ $result = new $1_ltype($1); %} %inline %{ #include using namespace std; struct XX { XX() { cout << "XX()" << endl; } XX(int i) { cout << "XX(" << i << ")" << endl; } XX(const XX &other) { cout << "XX(const XX &)" << endl; } XX & operator =(const XX &other) { cout << "operator=(const XX &)" << endl; return *this; } ~XX() { cout << "~XX()" << endl; } static XX create() { return XX(0); } }; %} ``` -------------------------------- ### Generate Python Wrapper for C Extension with SWIG Source: https://www.swig.org/Doc4.4/SWIGDocumentation.html/SWIGDocumentation This command runs SWIG with the `-python` option on the `example.i` interface file. It generates a C source file (`example_wrap.c`) and a Python source file (`example.py`) for creating a Python extension module from C code. ```Shell $ swig -python example.i ```