java - Use JNI to call C functions in host binary -


i'm trying call jni c function in executable hosting jvm. i've compiled -rdynamic, , confirmed nm -d symbol exported in dynamic symbols table. however, when call jvm complains symbol can't found.

i've done in past luajit , rather trivial, i'd pretty surprised if can't done java.

i created test method in class jnitest

public static native int strlen(); 

and implementation:

#include <jni.h> #include <java/com_jnitest_jnitest.h>  #include <string> #include <iostream>  jniexport jint jnicall java_com_jnitest_jnitest_strlen(jnienv* env, jclass clazz) {     return 1111; }  int main() {     jnienv* env;     javavm* jvm;      javavminitargs args;     javavmoption options[1];     args.version = jni_version_1_8;     args.noptions = 1;     args.options = options;     args.ignoreunrecognized = false;      std::string classpath = "-djava.class.path=";     classpath += "/var/projects/jnitest/src/java";     options[0].optionstring = (char*)classpath.c_str();      jint result = jni_createjavavm(&jvm, (void**)&env, &args);     if (result != jni_ok) {         std::cerr << "could not create jvm" << std::endl;         return 1;     }      jclass main_class = env->findclass("com/jnitest/jnitest");     if (main_class == nullptr) {         std::cerr << "could not find jnitest class" << std::endl;         return 1;     }      jmethodid main_method = env->getstaticmethodid(main_class, "main", "()v");      // call jnitest.main() transferring control java     env->callstaticvoidmethod(main_class, main_method, nullptr);      if(env->exceptioncheck()) {         env->exceptiondescribe();         return 1;     }      jvm->destroyjavavm();      return 0; } 

the jvm registers functions inside shared library if loaded system.loadlibrary().

since create jvm inside programm doesn't know function, can use env->registernatives(...) link native methods java class.

also jniexport not needed because register function pointer , there no need make method accessible outside.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -