Home > front end >  Using static C library from within go-code using SWIG
Using static C library from within go-code using SWIG

Time:05-26

How can I use C -code that uses static C -libraries from within a go file using SWIG (Simplified Wrapper and Interface Generator)?

(Note: The following post already describes the answer and a working solution)

I am using SWIG to implement the bridge in-between my C -code and my go-file. The C -code resides in a .cpp-file, which in turn calls a method from a static .a C -library that I created.

The question is, how to set up all parts appropriately in order to call a method from the static library from my go code.

This is my trivial setup:

Simple.cpp

#include "Simple.h"

int DoSimple()
{
    return 1701;
}

Simple.h

int DoSimple();

Foo.cpp

#include "include/Foo.h"

int foo()
{
    return DoSimple();
}

Foo.h

#include "d:\\home\\workspaces\\simple\\include\\Simple.h"

int foo();

swig.i

%module simple

%{
#include "include/Foo.h"
%}

%include "include/Foo.h"

main.go

package main

import "fmt"
import "awesomeProject/foo"

func main() {
    fmt.Println("Hello")

    a := simple.Foo()

    fmt.Println(a)

    fmt.Println("Bye")
}

I am creating the static and shared libraries out of these two files as so:

$ g   -c -o Simple.o Simple.cpp -Id:/home/workspaces/simple/include
$ g   -shared -o libSimple.so Simple.o
$ ar rcs libSimple.a Simple.o

I am then ending up having:

|-- simple/
       |-- include/
       |    |-- Simple.h
       |-- libSimple.a
       |-- libSimple.so
       |-- Simple.cpp
       |-- Simple.o


|-- foo/
      |-- main/
      |    |-- main.go
      |-- swig/
      |    |-- include/
      |           |-- Foo.h
      |    |-- Foo.cpp
      |    |-- simple.go
      |    |-- swig.i
      |    |-- swig_wrap.cxx

The two relevant go environment variables are set to:

$ go env -w CGO_LDFLAGS="-Ld:/home/workspaces/simple -lSimple"
$ go env -w CGO_CXXFLAGS=-Id:/home/workspaces/simple/include

Finally, I am issuing:

$ swig -go -c   -intgosize 64 ../foo/swig.i
$ go build -x .\main.go 

And surprise, surprise, the output is

$ go run main.go
Hello
1701
Bye

So, all good.

CodePudding user response:

Just by taking time to carefully formulate and post my question here on SO, I "accidentally" made it right and now it works.

Since I was almost done with my formulation - and to maybe further help other people having same or similar issues, I kept the post above.

  • Related