~andrewrk/ziglang

Building an Android JNI library with `zig --c-source`

Details
Message ID
<CACZYt3T8jACL+3Z_NMW8yYvcJ+5oyP=h1s2HHdDL_VxYQH5rzQ@mail.gmail.com>
Sender timestamp
1557784722
DKIM signature
missing
Download raw message
Hi!
I wanted to let you know, that with
https://github.com/ziglang/zig/pull/2477 merged today, I managed to
cross-compile a simple JNI .c to a .so library working on Android, as
part of an .apk, using Zig's builtin CC (as of the current
"master"/bleeding edge build of Zig).

The C file was from the following URL:
https://github.com/akavel/hellomello/blob/7a5b408fe52104c6787d40f741cd67db671d4ff9/exp/hello-jni.c
-- that is, the following code:

  #include <string.h>
  #include "jni.h"

  JNIEXPORT jstring JNICALL
  Java_com_akavel_hello2_HelloActivity_stringFromJNI( JNIEnv* env,
jobject thiz )
  {
      return (*env)->NewStringUTF(env, "Hello from JNI..!");
  }

plus a jni.h file copied from Android NDK, as present at:
https://github.com/akavel/hellomello/blob/7a5b408fe52104c6787d40f741cd67db671d4ff9/exp/jni.h.

The command line I used to build it (on Windows) was:
  c:> zig.exe build-lib -dynamic --verbose-cc --verbose-link
--c-source exp/hello-zig.c --library c -fPIC -target
armv7-linux-musleabi

Notably, I tried both -fPIC and -fno-PIC, and both seem to have
worked. I'm not sure which one is correct, at this phase I'm kinda
hacking forward more or less blindly, not looking around too much yet.

From what I found on the Internet, I seem to understand Android keeps
Linux syscalls untouched, so IIUC, statically linking musl should just
work (if wasting some space). I understand Android's own libc is a
custom one called "bionic". But again I'm not even sure if I correctly
assume that using a -musleabi target links musl statically?

As a follow-up, I wanted to ask if adding armv7a subarchitecture to
the cross-compilation targets was possible. But based on a snippet
from LLVM (https://github.com/llvm-mirror/llvm/blob/e132a1a24b971523cfc0f54fc539215df08ded62/lib/Support/Triple.cpp#L587-L589),
I guess the armv7 apparently already *is* armv7a? I must admit I'm
super confused by all the ARM subarchitectures, naming, flags,
features, etc... :/

Anyway, thank you very much for making Zig ship with a (comparatively)
small C cross-compiler, and for advertising this on lobste.rs! :)

Thanks & BR,
/Mateusz CzapliƄski.
Reply to thread Export thread (mbox)