Skip to content

Native code

Call system APIs, ship libraries and show views of your own on each platform, from pure Go to Objective-C, Win32, GTK, Java and the DOM, or put the app in a native project of your own.

NSGo has no plugin format of its own. Before writing platform code, look for the service among NSGo’s APIs (Platform services), and for a pure-Go library that does it. What is left goes in files built for each target, through what that target’s Go program can reach:

Target System calls A library of your own A view of your own (core.Native)
macOS, iOS, tvOS purego and its objc package A dylib or framework in nsgo-natives.yaml An NSView or UIView
Windows syscall, COM A DLL in nsgo-natives.yaml A child window
Linux purego A .so in nsgo-natives.yaml A GtkWidget
Android Through a Java class Java in android.classes A View class
Web syscall/js; the page’s host module JavaScript the host module imports A DOM element
HarmonyOS, watchOS, mini programs, terminal Pure Go only — —

What none of these can do, such as an Android manifest entry other than a permission or an Apple entitlement NSGo does not write, belongs to a native project of your own that embeds the app.

The Go program runs in the app’s process on every target, and on Android in a process of its own beside the Java runtime, with the app’s network permission either way. A Go library that uses only the standard library and pure-Go packages builds for every target without NSGo knowing about it, so prefer one wherever the work is a protocol, a file format or a codec.

A DLNA controller, for example, is pure Go: it finds renderers by sending SSDP’s M-SEARCH over UDP multicast and reading the replies, controls them with SOAP requests over HTTP, and can serve the media they play with net/http. Two platform rules still apply:

  • On iOS, and on macOS from 15, the user must let the app reach the local network: ask for core.PermissionLocalNetwork before the first search and explain it in apple.info’s NSLocalNetworkUsageDescription. Sending multicast from an iOS app also needs Apple’s com.apple.developer.networking.multicast entitlement, which a standalone build does not write yet; an embedding host adds it to its own target.
  • Android delivers multicast to an app only while it holds a Wi-Fi multicast lock, which the Go process cannot take. Replies to an M-SEARCH arrive by unicast and need none; a renderer’s own announcements need the lock, which a Java class can take (Android).

Put each target’s code in files its build tags select, such as cast_darwin.go, cast_windows.go and cast_android.go, behind one Go API the app calls. App code cannot use cgo on any target.

The app’s own code runs on the engine’s goroutine rather than the platform’s main thread, so an API that only the main thread may call goes through a native component, whose factory and methods run on the main thread. Register it with nsgo.Run(root, nsgo.Component(name, factory)) and show it with core.Native: its Props reach SetProp when they change, Ref.Command reaches Command, and what the component sends with NativeContext.Emit reaches OnEvent. A component with nothing to show takes a zero size. Only what View returns differs between targets, and the gallery’s components_*.go build one slider on each.

core.Native{
Component: "cast",
Ref: ref, // ref.Command("search", nil)
Props: map[string]any{"renderer": url},
OnEvent: func(name string, data any) { /* "found", … */ },
Style: core.Style{Width: core.Pt(0), Height: core.Pt(0)},
}

desktop.NativeWindow(cx) returns what system APIs take to name the window or panel cx’s view is in, and Window.NativeHandle the same for a window or panel the app holds, once its platform has created it: on macOS Handle is the NSWindow’s windowNumber, the CGWindowID that ScreenCaptureKit and CGWindowListCopyWindowInfo match, and Object the NSWindow itself, for AppKit calls in a native component on the main thread; on Windows Handle is the top-level HWND; on X11 it is the window’s XID, which GTK creates as the window first shows, so a window opened hidden has none until then. Both are tracked, so an effect hears the handle arrive. They return false on a closed window, in the app’s own scope where that is no window, on Wayland, which gives a window no global ID, on phones, on the web and in nsgotest’s headless model, where App.SetWindowEnvironment gives one window a handle.

cx.Effect(func() {
h, ok := desktop.NativeWindow(cx) // or w.NativeHandle() for a window the app opened
if !ok {
return // not created yet, closed, or no handle on this platform
}
switch h.Kind {
case desktop.NativeHandleAppKit:
excluded = append(excluded, uint32(h.Handle)) // a CGWindowID for SCContentFilter
case desktop.NativeHandleWin32:
hwnd = h.Handle // for IGraphicsCaptureItemInterop.CreateForWindow
case desktop.NativeHandleX11:
parent = fmt.Sprintf("x11:%x", h.Handle) // an XDG portal's parent_window
}
})

Reach Objective-C classes with purego’s objc package; the Go program is the app’s process.

//go:build darwin
import "github.com/ebitengine/purego/objc"
var sel = objc.RegisterName
func newLabel(cx *core.NativeContext) core.NativeComponent {
view := objc.ID(objc.GetClass("UILabel")).Send(sel("new")) // NSTextField on macOS
cx.SetSize(core.Size{Width: 220, Height: 28})
return &label{view: view, cx: cx} // View returns view
}

NSGo’s apple package gives such code what its own backends use, in files built for Apple’s targets:

  • apple.NewBlock and apple.NewBlockWithCleanup make the Objective-C blocks that completion handlers and enumerations take. Use them, not purego’s objc.NewBlock, whose block can point into a Go stack that has since moved. Release the returned block once the API it was passed to has copied it.
  • apple.OnMain runs a function on the main thread without waiting, for what only the main thread may call, such as presenting a system picker; the app’s own code runs on the engine’s goroutine. The functions run while the main thread’s run loop does: in a running app, in tests on an Apple target, and in headless macOS tests that call nsgotest.Main or nsgotest.MainFunc from TestMain. Testing
  • apple.WithAutoreleasePool runs a function in an autorelease pool on one OS thread, for Objective-C calls a goroutine makes, such as appending each frame a capture stream delivers.
//go:build darwin
handler := apple.NewBlock(func(_ objc.Block, content, err objc.ID) { /* … */ })
objc.ID(objc.GetClass("SCShareableContent")).Send(sel("getShareableContentWithCompletionHandler:"), handler)
handler.Release() // the framework copied it
apple.OnMain(func() { /* present SCContentSharingPicker */ })

objc.RegisterClass makes the targets and delegates that callbacks need. For what only Swift reaches, build a dynamic framework with Xcode that exports C functions with @_cdecl, declare its binary under ios and ios_simulator (or macos_arm64 as a dylib) in a Go package’s nsgo-natives.yaml, and load it with purego.Dlopen from the app’s Frameworks directory beside the executable (Native libraries).

Call Win32 through syscall.NewLazyDLL, and COM through its interfaces’ vtables. A component’s view is a child window, made with CreateWindowExW under a window class of your own, which follows its element. A DLL of your own goes under windows_x64 and windows_arm64 in nsgo-natives.yaml and loads from beside the executable.

//go:build windows
var (
user32 = syscall.NewLazyDLL("user32.dll")
createWindowEx = user32.NewProc("CreateWindowExW")
)

Load system libraries with purego.Dlopen and bind their functions with purego.RegisterLibFunc; NSGo already loads GTK 4 that way, and a component’s view is a GtkWidget pointer. A library of your own goes under linux_x64 and linux_arm64 in nsgo-natives.yaml, whose linux section names the distribution packages it needs (Linux packages).

//go:build linux && !android
gtk, err := purego.Dlopen("libgtk-4.so.1", purego.RTLD_NOW|purego.RTLD_GLOBAL)
purego.RegisterLibFunc(&gtkScaleNewWithRange, gtk, "gtk_scale_new_with_range")

The Go program cannot call Java directly: Java code reaches it as a View subclass that the Java runtime builds by reflection. Its Go component’s View returns the class’s name.

package com.example.cast;
public final class CastView extends android.view.View {
public interface OnFoundListener { void onFound(String location); }
public CastView(android.content.Context context) { super(context); }
public void setOnFoundListener(OnFoundListener l) { /* keep it, call it */ }
public void setRenderer(String location) { /* a prop */ }
public void search(double seconds) { /* a command */ }
}
//go:build android
type castView struct{}
func (castView) View() any { return "com.example.cast.CastView" }
func (castView) SetProp(string, any) {}
func (castView) Command(string, any) {}
func (castView) Close() {}
  • A prop calls the class’s one-argument set method of its name: renderer calls setRenderer. Values cross as JSON does.
  • ref.Command("search", []any{5.0}) calls the public search method whose parameters take those arguments.
  • Each setOn…Listener the class declares gets a listener whose callbacks reach OnEvent by their method’s name, with their arguments as a list: onFound brings []any{location}.
  • The class has a public constructor taking a Context, and lives only while its element is in the tree.

Compile the class and the Java libraries it uses with D8 (--min-api 28) into a .dex or a DEX JAR and list it under android.classes in nsgo.yaml, with the manifest permissions it needs beyond the runtime’s under android.permissions. The runtime already declares CHANGE_WIFI_MULTICAST_STATE, which a multicast lock needs. Preparing the DEX needs the Android toolchain; building the app does not.

android:
classes: [java/cast.jar]

The Android native example shows a class with a Go prop.

The app is WebAssembly in the page, so syscall/js reaches the browser’s APIs, and a component’s view is a DOM element. JavaScript of your own goes in the module web.host names in nsgo.yaml: its createHost(player) returns the host that answers cx.CallHost and cx.PostHost, as a page embedding the app does (Embedding).

//go:build js && wasm && !nsgoharmony && !nsgominiprogram
el := js.Global().Get("document").Call("createElement", "input")

HarmonyOS, watchOS, mini programs and the terminal

Section titled “HarmonyOS, watchOS, mini programs and the terminal”

These targets host no native components of an app’s own and load no libraries it declares: what NSGo’s APIs do not cover is pure Go there. A mini program’s core.Native reports errors.ErrUnsupported through OnError.

When the app needs what a standalone build cannot declare, build it with -embed and put it in an Xcode, Gradle or Go project of your own, or a web page. The host writes the native code in its own language, registers native components with each view, and answers the app over the host channel: cx.CallHost and cx.PostHost call the host’s handlers, and cx.OnHostEvent hears what it sends. The Embedding page shows each host.