JNI question

Started by
3 comments, last by Aliii 11 years, 11 months ago
Ive just started to learn JNI. It seems like: I call a native function, the function does its job, returns something, and thats all. Is there a way to make the native part "remember" data, that I send from Java? ....so I dont have to send it in every iteration, when its constant data. Can I make a native thread, and use "global native variables" with JNI? Thanks very much!
Advertisement
JNI is just a function call, nothing more. It is no different than calling a function in Java or C++ or python or perl or whatever other language you are interfacing with.

You'd need to write your native library in such a way that it keeps a copy of the data. Otherwise you'll need to just keep sending a copy every time.
You'd need to write your native library in such a way that it keeps a copy of the data.

Thanks! But how can I do that? Im using android NDK, trying to write cpp functions. It compiles the cpp files, puts the .so files into the project/jni folder, and then I can call the functions ....thats all I know about it. How Java calls the native functions, how it "switches" from VM to native, where are the native functions/data in the memory, does Java clear that memory after the functions return ....I dont know.
Here is example of C++ code:static int global = 0;

JNIEXPORT void JNICALL Java_com_example_YourClass_add(JNIEnv* env, jclass klass, jint value)
{
global += value;
}

JNIEXPORT jint JNICALL Java_com_example_YourClass_getSum(JNIEnv* env, jclass klass)
{
return global;
}


You wrap it with this Java code:
package com.example;

class YourClass
{
static {
System.loadLibrary("...");
}

public static native void add(int value);
public static native int getSum();
}


Does that clear up things? Of course, its a bit bad example, because it uses global variables. But you can always return Java class instance (jobject) that stores needed data.

Java only clear memory for things allocated through JNI. You are resposnible for everything else (fopen, new, malloc, ...)

Here is example of C++ code:static int global = 0;

JNIEXPORT void JNICALL Java_com_example_YourClass_add(JNIEnv* env, jclass klass, jint value)
{
global += value;
}

JNIEXPORT jint JNICALL Java_com_example_YourClass_getSum(JNIEnv* env, jclass klass)
{
return global;
}


You wrap it with this Java code:
package com.example;

class YourClass
{
static {
System.loadLibrary("...");
}

public static native void add(int value);
public static native int getSum();
}


Does that clear up things? Of course, its a bit bad example, because it uses global variables. But you can always return Java class instance (jobject) that stores needed data.

Java only clear memory for things allocated through JNI. You are resposnible for everything else (fopen, new, malloc, ...)


Thanks! It works

This topic is closed to new replies.

Advertisement