Search code examples
javac++jna

java-JNA call a native loop from Java and stop it from an other function


I want to start a loop coded in C++ that is run untill I ask it (from Java) to stop. IE:

(in c++)

void loop(){
   while(!stop){
     // do something
   }
}

in Java:

MyLib.INSTANCE.loop();

then call something like : MyLib.INSTANCE.stop = true;

Is it possible ?


Solution

  • While you can access a shared library's globals (NativeLibrary.getGlobalVariableAddress()), it's preferable to define a dedicated function which does what you want (i.e. MyLib.stop()).

    You also need to take care that your code is multi-thread aware, so that the compiler doesn't think your loop's stop cannot be changed and thus optimizes it away. You also need to ensure that your loop doesn't monopolize the CPU; it needs to yield from time to time if you want your "stop" code to be able to run.