SWIG (Simplified Wrapper and Interface Generator)

4.4.1 · active · verified Sat Apr 11

SWIG is a software development tool that facilitates connecting programs written in C and C++ with a variety of high-level programming languages, including Python. It works by generating 'wrapper' code that allows scripting languages to access underlying C/C++ code. The current version is 4.4.1, with releases focused on C/C++ standard improvements, expanded language support, and Python compatibility updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the full SWIG workflow: defining C/C++ functions, creating a SWIG interface file (`.i`), using the `swig` command to generate Python wrapper code and a Python module file, compiling the C/C++ source with the generated wrapper, linking them into a shared library, and finally importing and using the module in Python. Note that the compilation commands (g++) are platform-dependent and assume a C++ compiler and Python development headers are installed.

/* C/C++ file: example.h */
#ifndef EXAMPLE_H
#define EXAMPLE_H

int fact(int n);
int my_mod(int x, int y);

#endif // EXAMPLE_H

/* C/C++ file: example.c */
#include "example.h"

int fact(int n) {
    if (n < 0) return 0; /* Or handle error appropriately */
    if (n == 0) return 1;
    return n * fact(n - 1);
}

int my_mod(int x, int y) {
    if (y == 0) return 0; /* Or handle error appropriately */
    return x % y;
}

/* SWIG interface file: example.i */
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

int fact(int n);
int my_mod(int x, int y);

# Build and run steps in bash
# 1. Generate SWIG wrapper code
# swig -python -c++ example.i

# 2. Compile C/C++ source and SWIG wrapper
# g++ -c example.c example_wrap.cxx -I/usr/include/python3.10 -fPIC

# 3. Link into a shared library
# g++ -shared example.o example_wrap.o -o _example.so

# Python usage:
import example

print(f"Factorial of 5: {example.fact(5)}")
print(f"7 mod 3: {example.my_mod(7, 3)}")

view raw JSON →