whoami
Lucas Jenß
cat /etc/motd
The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.
ls -la ~/languages/
- drwxr-xr-x
- ▶ PHP
- ▶ Ruby
- ▶ Scala
- ▶ C#
- ▶ JavaScript
- ▶ Objective-C
- ▶ Shell Scripting
ls -la ~/toolchain/
- drwxr-xr-x
- ▶ Typo3
- ▶ Akka
- ▶ Capistrano
- ▶ Git
- ▶ MAMP
- ▶ Adobe Illustrator
- ▶ NSTrackingArea (Cocoa)
uname -a
- drwxr-xr-x
- ▶ Mac OS X
- ▶ Unix
Calling Java From Native C With Android NDK JNI
Android applications can split work between Java or Kotlin and native C or C++ code. The Android NDK supplies the native toolchain, while the Java Native Interface (JNI) provides the bridge between the two runtimes. When C needs to trigger a Java method, the native code must locate the correct class, resolve its method signature, and invoke it through a JNIEnv pointer.
This pattern is useful for legacy C libraries, performance-sensitive routines, hardware integrations, and code shared with other platforms. It is also easy to make fragile: a wrong JNI signature, an invalid local reference, or a native thread that was never attached to the virtual machine can produce crashes that look unrelated to the original call.
The examples below use a Java activity and a C implementation built with the Android NDK. The same principles apply when the Java side is written in Kotlin, although Kotlin methods may generate different JVM names and overloads. Test the bridge on the Android versions and device types that matter to your application, including the varied handsets commonly used across Sydney, Melbourne and regional Australia.
| Requirement | Java side | Native C side |
|---|---|---|
| Declare the bridge | native method |
Implement matching JNI function |
| Find a method | Java method name and types | GetMethodID with JNI signature |
| Call a method | Ordinary Java method | CallVoidMethod, CallObjectMethod, or similar |
| Pass text | String |
jstring, usually created with NewStringUTF |
| Handle failures | Java exception | ExceptionCheck, logging and cleanup |
| Use another thread | Normal Java thread | Attach with AttachCurrentThread |
Define A Small Java Native Boundary
Keep the Java-facing API narrow. A simple method gives native code a stable entry point without exposing implementation details:
package com.example.bridge;
public class NativeBridge {
public native void sendMessage(String message);
public void displayMessage(String message) {
android.util.Log.i("NativeBridge", message);
}
static {
System.loadLibrary("native-lib");
}
}
The sendMessage declaration tells Java that the implementation is in a shared native library. The native method can then call displayMessage, which is an ordinary instance method. In a real application, the bridge object might forward data to an activity, service, or repository, but it is safer to keep Android lifecycle logic outside the C layer.
The C implementation needs JNI headers and a function whose name matches the package, class and native method. For the declaration above, the conventional exported name is Java_com_example_bridge_NativeBridge_sendMessage. A registration table with RegisterNatives is another option and avoids long symbol names, but the conventional approach is convenient while learning or maintaining a small project.
Match Classes And Signatures Precisely
JNI method lookup depends on the JVM class name, method name and method signature. Java package separators become slashes when looking up a class:
jclass bridge_class = (*env)->FindClass(
env, "com/example/bridge/NativeBridge"
);
jmethodID display_id = (*env)->GetMethodID(
env, bridge_class, "displayMessage", "(Ljava/lang/String;)V"
);
The signature (Ljava/lang/String;)V means one java.lang.String argument followed by a void return value. Common descriptors include I for int, Z for boolean, J for long, D for double, and V for void. An object type uses Lfully/qualified/ClassName;, while arrays begin with [. A method accepting an integer and returning a string would therefore use (I)Ljava/lang/String;.
A frequent mistake is writing a source-level type such as String or void in the signature. JNI uses JVM descriptors instead. Another is confusing an instance method with a static method. Use GetMethodID and Call<Type>Method for an object method; use GetStaticMethodID and CallStatic<Type>Method for a static method.
Invoke The Java Method From C
The native function receives a JNIEnv *, a Java object representing this, and the Java string argument:
#include <jni.h>
JNIEXPORT void JNICALL
Java_com_example_bridge_NativeBridge_sendMessage(
JNIEnv *env, jobject thiz, jstring message) {
jclass cls = (*env)->GetObjectClass(env, thiz);
jmethodID method = (*env)->GetMethodID(
env, cls, "displayMessage", "(Ljava/lang/String;)V"
);
if (method == NULL) {
return;
}
(*env)->CallVoidMethod(env, thiz, method, message);
}
The JNIEnv interface is represented with function-table syntax in C. In C++, the equivalent call is usually written as env->GetMethodID(...), which is one reason JNI examples can look different between C and C++ projects. The thiz reference is valid for the duration of this native call and is the object on which the Java method executes.
If the native code needs to create a message rather than forward an existing argument, use NewStringUTF for modified UTF-8 text:
jstring text = (*env)->NewStringUTF(env, "Called from native C");
(*env)->CallVoidMethod(env, thiz, method, text);
(*env)->DeleteLocalRef(env, text);
NewStringUTF is not a general-purpose UTF-8 decoder for arbitrary byte streams. For user-entered text, explicitly convert according to the encoding contract of the native library. This matters for international names and addresses, including Australian users whose data may contain accented characters or non-Latin scripts.
Check Exceptions And Manage References
A Java exception raised during a JNI call remains pending on the thread. Native code should check it before continuing:
(*env)->CallVoidMethod(env, thiz, method, message);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
Whether to clear the exception depends on the application’s error policy. Clearing it prevents the exception from propagating, but it can hide a genuine failure. In many cases, describe the exception for diagnostics, release native resources, and return so Java can handle the error through a deliberate mechanism.
Local references are automatically released when the native method returns, but loops can exhaust the local reference table. Delete temporary classes, strings and objects during long-running work with DeleteLocalRef. A class or method ID can be cached, although a jclass found through FindClass should be converted to a global reference if it must survive the current call:
jclass local_class = (*env)->GetObjectClass(env, thiz);
jclass global_class = (*env)->NewGlobalRef(env, local_class);
(*env)->DeleteLocalRef(env, local_class);
Use global references sparingly and release them with DeleteGlobalRef. Leaking them can keep Java objects alive and eventually cause memory pressure. Android applications distributed through the Australian market may run for long periods on budget devices, so reference leaks are especially visible in field testing.
Handle Native Threads Safely
The JNIEnv * belongs to the current thread. It must not be stored and reused from an arbitrary worker thread. A native thread created with pthread_create is not automatically attached to the Android runtime, so it must attach through the JavaVM first.
Store a JavaVM * during JNI_OnLoad:
static JavaVM *g_vm;
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
g_vm = vm;
return JNI_VERSION_1_6;
}
A worker can then obtain an environment:
JNIEnv *env = NULL;
jint result = (*g_vm)->AttachCurrentThread(g_vm, &env, NULL);
if (result == JNI_OK) {
/* Find or call Java methods here. */
(*g_vm)->DetachCurrentThread(g_vm);
}
The exact attach signature can vary slightly between C and C++ declarations, so follow the headers included by the NDK version in your build. Every thread attached by native code should be detached before it exits. Keep a global reference to any Java object used by the worker; a local reference from an earlier JNI call is not sufficient.
Threading bugs often appear only under load. They can surface when a commuter opens an app repeatedly on a Sydney train connection or when background work resumes after the device has been idle. Add clear lifecycle rules for stopping workers before an activity or service is destroyed.
Build, Log And Debug The Bridge
With CMake, link the native target against the Android log library when diagnostic output is useful:
find_library(log-lib log)
target_link_libraries(native-lib
${log-lib}
)
Native logging can be written with __android_log_print. A practical Android Logcat guide is useful when checking method IDs, thread attachment and pending exceptions on a physical device.
Use adb logcat, Android Studio’s debugger, and sanitising tools to separate a JNI lookup problem from a native memory error. Confirm that the package name in the C symbol matches the compiled Java class, that the shared library name matches System.loadLibrary, and that the ABI is included in the APK or app bundle. Build and test arm64-v8a at minimum for current devices, while considering other ABIs if your supported hardware requires them.
A bridge can also expose sensitive data through logs. Australian businesses handling personal information should consider obligations under the Privacy Act 1988 and the Australian Privacy Principles. Avoid logging tokens, account details or full user messages in production, and review retention practices before shipping an app to customers in Brisbane, Perth or elsewhere.
When the Java call works, document its signature beside the native implementation and add a small automated test for each argument type. Keep the interface stable, release references deliberately, and record failures in a way that preserves the original Java exception rather than replacing it with an opaque native error.
For related systems thinking around cross-process communication and configuration, see these notes on Akka SSL configuration. The same discipline applies here: define the boundary clearly, verify the contract at runtime, and make failures observable.
Try the bridge first with a single String argument, then add numbers, return values and worker-thread calls one at a time. Keep the smallest working example in your project’s troubleshooting notes, alongside the NDK version, Android API level and tested device models. Further development notes and experiments are collected on Mike Meredith’s blog, providing a useful reference when a JNI issue turns into a broader native Android investigation.
cat ~/interests.json
| Key | Value |
|---|---|
| editor | Terminal-first workflow |
| os | Mac OS X / Unix |
| vcs | Git, distributed version control |
| deploy | Capistrano, cron automation |
| graphics | SVG, Adobe Illustrator troubleshooting |
| networking | IP validation, SSH, VPN |
git log --oneline --reverse
Solving SVG import issues in Adobe Illustrator CS6 and CC
When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.
Solving NDK build issues on OS X
Troubleshooting native development kit compilation problems on Mac OS X.
Programmatically adding PHP generated TypoScript to the backend configuration
Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.
ArgumentError: Could not parse PKey: no start line
Debugging an SSH key parsing error encountered during deployment.
Validating IP-Addresses in PHP
Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.
Cocoa: Using NSTrackingArea
A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.
cat ~/contact.txt