Scapix JNI

github: scapix-jni

Modern C++20 wrapper for JNI:

  • type-safe APIs
  • automatic resource management
  • ZERO runtime overhead compared to manually written JNI code
  • automatic C++/Java type conversion for many standard types (std::string, std::vector, etc.)
  • automatic C++/Java exception tunneling
  • comes with pre-generated C++ headers for all JDK and Android Java APIs
  • automatically generate C++ headers for any Java code, including your own

Example without generated headers:

#include <scapix/jni/object.h>

namespace jni = scapix::jni;

void test_string()
{
    auto str = jni::new_object<jni::object<"java/lang/String">, void()>();
    auto length = str->call_method<"length", jint()>();
}

Same code using generated headers:

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

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

void test_string()
{
    auto str = jni::new_object<java::lang::String>();
    auto length = str->length();
}

Calling standard JDK functions with automatic type conversion:

#include <scapix/java_api/java/lang/System.h>
#include <scapix/java_api/java/util/Locale.h>
#include <scapix/java_api/java/text/DateFormatSymbols.h>

using namespace scapix::java_api;

void test()
{
    // C++ objects are automatically converted to and from corresponding Java types.
    // This works for any type supported by scapix::link::java::convert<> interface,
    // which supports many STL types and can be extended for your own types.

    std::string version = java::lang::System::getProperty("java.version");
    std::vector<std::string> languages = java::util::Locale::getISOLanguages();
    std::vector<std::vector<std::string>> zone_strings = java::text::DateFormatSymbols::getInstance()->getZoneStrings();
    std::map<std::string, std::string> properties = java::lang::System::getProperties();
}