Ebitengine is a Go game development engine. Games can be built for Linux, MacOS, Windows, Android, iOS and Nintendo Switch.
I did some basic experiments during a few vacation days. This post is about something which wasn’t obvious to me how to implement and took me some hours to figure out. Hopefully it may spare you some time.
Under the hood Ebitengine uses gomobile to create bindings for languages like Java and C/C++.
This article is especially interesting if you need to call Go functions from Java or C/C++ and vice-versa.
What is the problem
I make a Go game which runs on Android, but I’d like to show Ads using 3rd party
SDK like Unity or Facebook Audience Network. This means I’ll have to integrate
a Java or ObjC library in the native app. For example, on Android it could be
implemented in the showAds
method below:
|
|
The problem is that MainActivity
doesn’t know when to call show ads, as it doesn’t know anything
about the internal state of the game - game updates and state changes happen in the Go code.
So, at any point in time, only the Go side knows if it’s time to show an advert. Now the problem
comes down to how the Go code can call the showAds()
Java method?
Solution
My current solution is presented below and it works. I don’t feel it optimal since it requires to keep a global variable reference to the game object, but for now I haven’t found an improvement (and I don’t know if it’s an issue at all).
It shows how to call Go functions from Java as well as Java functions from Go.
Go
First, we must tell the Go side what function it should call to show ads, as it doesn’t know
anything about the existence of the MainActivity.showAds
method. This means I must call a Go
function from Java to register the callback.
To do that I define an exported Go function in the mobile.go
file which will be used to
produce the bindings. The function will be exported as static class method on the Java side.
I also define an interface for the object that I expect to receive as an argument.
The object must implement a method called showAds
and will be implemented on the Java side.
The exported function RegisterAdsCallback
is used from Java to give this object to the Go side.
|
|
Now when I produce the Java library containing the game with ebitenmobile
,
the class Mobile
will have this RegisterAdsCallback
static method, which can
be used from Java to register the showAds
method.
|
|
Java
In Java we implement the callback and give it to the Go side.
|
|
Usage in Go
Whenever the Go game decides that it’s time to show ads, it can invoke game.showAds()
:
|
|