tags:

views:

415

answers:

1
+1  Q: 

callbacks in jni

Is there any way to pass a callback to java code, from C. And the call returns immediately. Later on, after completing the task, the java code can invoke that callback.

I have a C extension for php that calls a java store to store some items in it. The items can be retrieved from store in synchronous and asynchronous methods (I provide the store with list of keys and a callback and it invoke the callback and return the item in it).

I am able to retrieve the items synchronously from extension, but now I don't know how to do it asynchronously.

  • Is there any way that my C code can give a pointer to function that java can later invoke?
  • OR is it possible that I create a java thread everytime C code asks to retrieve items asynchronously, and that java thread then invoke a C function that can return the items back to user?

As a last resort I may have to create a thread in C code and queue up keys in that thread that it can retrieve from java.

Or is there any support in zend that allows me to queue up tasks and a callback that zend can invoke one by one for every task in queue?

+1  A: 

The way for java to call C functions is native class methods. Just make some class in java (probably implementing your callback interface) that has native method. Compile it and process with javah tool from JDK - this creates header with function signature. Then you can implement this function in your native code.

When you need to supply callback - create a new instance of this class via NewObject() and pass to java code.

Xeor
Will that native function call give me a valid JniEnv pointer, the one that is already loaded by C program? Is it important to create a new instance of class and pass it to java? Can you provide me some sample code.
cornerback84
For example function declared native int callback(string); will have C signature jint Java_com_mypackage_MyClass_callback(JNIEnv *env, jobject class_instance, jstring parameter) - you have env, pointer to class with callback and all the parameters. I'll try to provide sample code later
Xeor