Native Methods

Implementing Native Methods

package com.scapix.example1;

public class Class1
{
	public native java.lang.String function1(java.lang.String[] strings);
	public static native java.lang.String function2(java.lang.String[] strings);
	public static native java.lang.String function3(java.lang.String[] strings);
	public native java.lang.String function4(java.lang.String[] strings);

	static { System.loadLibrary("example1"); }
}

Declare native methods using jni::native_methods<> template and jni::native_method() function. This creates constexpr array of JNINativeMethod entries at compile time.

For an instance method, the first parameter must be ref<object<"com/scapix/example1/Class1">> (or compatible). For a static method, the first parameter must be ref<class_> (or compatible). If all parameters are JNI types, JNI signature can be deduced. If you omit ref<class_> first parameter for a static method or use any C++ type parameters, you must specify JNI signature. Additionally, you can specify C++ signature to select overload.

#include <scapix/jni/native_method.h>
#include <scapix/java_api/java/lang/String.h>

namespace example1 {

namespace jni = scapix::jni;
using namespace scapix::java_api;

jni::ref<java::lang::String> class1_function1(jni::ref<jni::object<"com/scapix/example1/Class1">>, jni::ref<jni::array<java::lang::String>>);
jni::ref<java::lang::String> class1_function2(jni::ref<jni::class_>, jni::ref<jni::array<java::lang::String>>);
jni::ref<java::lang::String> class1_function3(jni::ref<jni::array<java::lang::String>>);
std::string class1_function4(std::vector<std::string>);

using class1_native_methods = jni::native_methods
<
	"com/scapix/example1/Class1",

	jni::native_method("function1", class1_function1),
	jni::native_method("function2", class1_function2),
	jni::native_method<jni::ref<java::lang::String> (jni::ref<jni::array<java::lang::String>>)>("function3", class1_function3), // must specify signature, missing ref<class_> first parameter
	jni::native_method<jni::ref<java::lang::String> (jni::ref<jni::array<java::lang::String>>)>("function4", class1_function4), // must specify signature, C++ type parameters
>;

} // namespace example1

Register native methods in JNI_OnLoad():

#include <scapix/jni/module.h>
#include <example1/class1.h>

namespace jni = scapix::jni;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
	return jni::on_load(vm, reserved, []
	{
		example1::class1_native_methods::register_();
	});
}