Skip to content

Instantly share code, notes, and snippets.

@Shikugawa
Created January 26, 2020 17:54
Show Gist options
  • Save Shikugawa/49454b3644a90e8a3ccb149ec2d3a7e4 to your computer and use it in GitHub Desktop.
Save Shikugawa/49454b3644a90e8a3ccb149ec2d3a7e4 to your computer and use it in GitHub Desktop.
Call C++ Library from Go using shared library with SWIG

Introduction

SWIG can generate interface for other languages to call C++ functions. If C++ codes are separeted to mutiple directories, we may have some trouble.

Build Flow

  1. Prepare directories like this.
- invoke
  - invoke.cpp
  - invoke.hpp
- lib.cpp
- lib.hpp
- lib.i
%module lib
%{
#include "lib.hpp"
%}

%include "lib.hpp"

Other files are described in go_cpp_linkage.md.

  1. Create shared library
clang++ invoke.cpp -shared -fPIC -o libinvoke.so
  1. Genarate glue codes
swig -go -c++ -cgo -intgosize 64 lib.i
  1. Add to enable dynamic linking to lib.go
  ・
  ・
  ・
// source: lib/lib.i

package lib

/*
#cgo LDFLAGS: -L ./ -linvoke -ldl
  ・
  ・
  ・
  1. Check your LD_LIBRARY_PATH. If it is not included the location of libinvoke.so, you must add them to it.
export LD_LIBRARY_PATH=~/go/src/github.com/Shikugawa/go-cpp-ffi/lib:$LD_LIBRARY_PATH
  1. Build
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment