Skip to content

Export go pkgs as native .dll/.so using c-shared

License

Notifications You must be signed in to change notification settings

imacks/golib-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

golib-demo

This repo demonstrates how to build Golang packages as DLL/SO dynamic library.

Ref. https://github.com/golang/go/wiki/cgo

Windows DLL

Using example in src/goutil

Run script below in Linux env docker: cr.lizoc.com/dockerguys/golang:1.14

apk-install git mingw-w64-gcc
mkdir /go/src/testlab && cd /go/src/testlab
git clone https://github.com/imacks/golib-demo.git ./
cd src/goutil
GOOS=windows CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ CGO_ENABLED=1 \
    go build  -ldflags="-s -w" -buildmode=c-shared -o /go/bin/libgoutil.dll ./main.go
ls /go/bin/libgoutil.*

Copy out to host and then FTP to Windows box:

docker cp testgo:/go/bin/ ./

Test dll works on Windows x64, using PowerShell/.NET:

$libsrc = @'
   [DllImport("C:\\libgoutil.dll", EntryPoint="Greet")]
   public static extern void Greet();

   [DllImport("C:\\libgoutil.dll", EntryPoint="Add")]
   public static extern int Add(int a, int b);

   [DllImport("C:\\libgoutil.dll", EntryPoint="Minus")]
   public static extern int Minus(int a, int b);
'@
$testlib = Add-Type -MemberDefinition $libsrc -Name 'TestLib' -PassThru -Namespace System.Runtime.InteropServices
$testlib::Greet()
$testlib::Add(5, 3)
$testlib::Minus(5, 3)

Linux .SO

Building on Alpine still doesn't work. Use golang on debian buster (golang:1.14):

mkdir /go/src/testlab && cd /go/src/testlab
git clone https://github.com/imacks/golib-demo.git ./
cd src/goutil
# must prefix with 'lib'
GOOS=linux CGO_ENABLED=1 go build  -ldflags="-s -w" -buildmode=c-shared -o /go/bin/libgoutil.so ./main.go
ls /go/bin/libgoutil.*

cd ../cgtest
gcc -I/go/bin -o /go/bin/cgtest main.c -L/go/bin -lgoutil -Wl,-R '-Wl,$ORIGIN'
# test
/go/bin/cgtest

About

Export go pkgs as native .dll/.so using c-shared

Resources

License

Stars

Watchers

Forks

Packages

No packages published