What are the best practices when using SWIG with C#?

Dale Ragan picture Dale Ragan · Aug 24, 2008 · Viewed 9.1k times · Source

Has anybody out there used the SWIG library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application.

Edit: Some clarification on target OS's.

I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.

Answer

Marc Bernier picture Marc Bernier · Jul 1, 2009

For my last project, here's the entire C# SWIG configuration file:

%module mdProject

%{
#include "mdProject.h"
%}

I compiled it in SWIG with:

swig -csharp -c++ -I../../Include mdProject.i

This generated a Project.cxx which I compiled and linked directly into the 'main' DLL, so I didn't need a second C++ 'helper' DLL. SWIG also generated a bunch of C# files which I compiled into a .NET DLL. My other wrappers (Java, PHP, etc) do use a helper DLL.

As @patrick mentioned, SWIG uses P/Invoke, so if you have a problem with that, you'll need to find another solution.

If you use types that stray from the ordinary (voids, structures, etc), you will have to do some extra work to get it right, but for the average API using int's, char*'s etc, it's fine.