LoginSignup
2
2

More than 5 years have passed since last update.

GomobileからShared libraryを出力してみた

Last updated at Posted at 2016-09-11

前回書いた「Gomobileで作ったAARをばらしてShared LibraryだけをUnityで動かしてみた」では関数のコールが長くて気持ち悪かった。
golang/mobile/cmd/gomobile/bind_test.go」を参考にビルドコマンドを調べてみた。

抜粋したビルドコマンドはこんなの

GOMOBILE=$GOPATH/pkg/gomobile \
GOOS=android \
GOARCH=arm \
NDK=ndk-r12b \
CC=$GOMOBILE/android-${NDK}/arm/bin/arm-linux-androideabi-clang \
CXX=$GOMOBILE/android-${NDK}/arm/bin/arm-linux-androideabi-clang++ \
CGO_CFLAGS="-target armv7a-none-linux-androideabi --sysroot $GOMOBILE/android-${NDK}/arm/sysroot" \
CGO_CPPFLAGS="-target armv7a-none-linux-androideabi --sysroot $GOMOBILE/android-${NDK}/arm/sysroot" \
CGO_LDFLAGS="-target armv7a-none-linux-androideabi --sysroot $GOMOBILE/android-${NDK}/arm/sysroot" \
CGO_ENABLED=1 GOARM=7 go build -pkgdir=$GOMOBILE/pkg_android_arm \
-tags="" -x -buildmode=c-shared \
-o=./hoge/libhoge.so \
hoge.go

コードはCommand cgoにあるようにexportつけておけば良いようだ。

hoge.go
package main

import "C"

//export MyFunction
func MyFunction() int {
  return 10
}

func main() {
}

実行すると./hoge/libhoge.so./hoge/libhoge.hが出力される
libhoge.soをUnityの環境に配置し、クリックで加算する処理で実行した。

ButtonTest.cs
using UnityEngine;
using System.Runtime.InteropServices;

public class ButtonTest : MonoBehaviour {

    int gnum = 0;

    [DllImport("hoge")]
    private static extern int MyFunction();

    public void TestClick()
    {
        int num = MyFunction();
        Debug.Log(num);
        gnum += num;
    }

    void OnGUI(){
        GUI.Label (new Rect (0, 0, 100, 30), gnum.ToString());
    }
}

無事に、短い関数名でコールできるようになりました。

nm data section

参考までに nm data section

% nm -D libhoge.so | grep -i MyFunction
0006d548 T MyFunction
00012000 T _cgoexp_df1f512bfd60_MyFunction

その他

x86のビルドコマンドはどこにあるのだろう?

mobile/cmd/gomobile/env.goを参考にすると下記が書いてあるんだが。。

"386": {
    arch:       "x86",
    abi:        "x86",
    platform:   "android-15",
    gcc:        "x86-4.9",
    toolPrefix: "i686-linux-android",
    minGoVer:   go1_6,
},

また今度探してみよう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2