//go:build android package native import ( "encoding/binary" "errors" "fmt" "sync/atomic" "github.com/egoist/mygo/internal/nativehost" ) // On Android a module is implemented in Kotlin, which Go calls through // JNI (nativehost.Kotlin, which the host's Go side sets): the generated // Kotlin object of the module decodes the arguments, calls the // implementation and encodes its answer, as a Swift library's C functions // do elsewhere. Kotlin tells Go what happens later through one native // method, which reaches handle as purego's callback does on desktops. // lastModule numbers the modules as they load. var lastModule atomic.Uint64 // library is a module's Kotlin, by the name it registered under. type library struct{ name string } func init() { nativehost.Handle = func(kind, id uint64, status int64, data []byte) (int64, []byte, bool) { st, out, ok := handle(kind, id, status, data) if !ok { return 0, nil, false } b := append([]byte(nil), out.bytes()...) out.release() return st, b, true } } func (m *Module) load() (*library, error) { m.once.Do(func() { m.lib, m.err = m.open() }) return m.lib, m.err } func (m *Module) open() (*library, error) { k := nativehost.Kotlin if !m.supported() { return nil, errors.ErrUnsupported } if k == nil { return nil, errors.New("native: the app's host has no native modules: build it with mygo build -platform android") } for _, name := range m.Deps { dep := registered(name) if dep == nil { return nil, fmt.Errorf("native: %s uses the native module %s, which the program does not link", m.Name, name) } if _, err := dep.load(); err != nil { return nil, err } } idx := lastModule.Add(1) modules.Store(idx, m) if msg := k.Init(m.Name, m.Kotlin, idx<