jni not support types as void*, unsigned int*, … What to do?

前端 未结 4 521
失恋的感觉
失恋的感觉 2021-01-13 22:46

I have .so (shared library) written in C++, lets call it functionality.so in which I implement different functions, here is list of some fu

4条回答
  •  耶瑟儿~
    2021-01-13 23:14

    You can use jlong to pass a pointer (or a pointer to pointer, or whatever) back to Java. Java code won't be able to use it for anything, other than passing it as an argument to one of your other methods; but often that's all you really want. If, on the other hand, you want Initialize() to be called with data set up in Java, then void * isn't appropriate; you'll need to use a Java class, and use reflection in JNI to get the information you need out of it.

    Crudely, you could wrap malloc() and free():

    jlong Java_c_utils_malloc(JNIEnv* env, jclass clazz, jint size) {
        return (jlong) malloc(size);
    }
    
    void Java_c_utils_free(JNIEnv* env, jclass clazz, jlong ptr) {
       free((void *) ptr);
    }
    

    and then use them (to no effect!) in Java:

    long ptr = utils.malloc(100);
    // Store ptr for a while
    utils.free(ptr);
    

    Now, if we wrapped some other functions that needed a block of memory as an argument, we could wrap them too, and let them accept a jlong argument, the same way free() does. The fact that the Java variable ptr represents a memory address is completely opaque in Java, but it's useful nonetheless.

    Window system implementations for Java (i,e., AWT, SWT) use this same sort of thing to associate the native widget handle with the Java component.

    Now, if you want your Initialize() to be able to take useful arguments from Java, then a void * isn't going to cut it. You'd need to write your method to accept a Java object as an argument; that's the only way to allow you to manipulate the object in Java.

    I don't want to duplicate all the code here, but Sun's JNI tutorial is here. This is the section on calling arbitrary methods of a Java object (either the this object, or one passed to your method as an argument) and this is an analogous section on accessing the fields of an object.

提交回复
热议问题