2

In my JNI project I need to add events/callbacks to the java client that will receive this event from the native library. In c++ I do it this way:

Dialog based:

SetProcessEventCallback((ProcessEvent) KSampleDlg::OnProcessEvent, this);

void KSampleDlg::OnProcessEvent(float fPercent, float fDeviceBuffer, float fCache, double dBytesWritten, double dImageSize, KSampleBurnDlg *pDlg) 
{
    pDlg->SetProgress((int)fPercent, (int)fCache);
}

In console app It works like

SetProcessEventCallback(OnProcess, 0);

void OnProcess(float fPercent, float fDeviceBuffer, float fCache, 
               double dBytesWritten, double dImageSize, void *pUserData)
{
    static int nChars = 0;
    g_cOutputLock.Lock();

    while( (fPercent/100.0)*80 > nChars )
    {
        g_strBuffer += _T("*");
        nChars++;
    }
    g_cOutputLock.UnLock();
}

After this event callback is set the library will fire this event to the given function. I can set the function and callback in the native lib but I have no idea how to fire this to the java app. Anyone can give me a hint how to handle this with JNI?

IFDev
  • 55
  • 7
  • 1
    On what thread does the callback run? I feel like you may have to do something like as in [this question](https://stackoverflow.com/questions/43682803). – HTNW Nov 24 '20 at 07:36
  • If you only want to communicate a percentage, you can also just use a plain pipe between Java and C++ and skip JNI. – Botje Nov 24 '20 at 08:46
  • @Botje - do you have more information about this? – IFDev Nov 24 '20 at 10:58
  • See also [the answer here](https://stackoverflow.com/questions/63581654/swig-java-how-do-i-pass-a-struct-with-callback-functions-to-c-from-an-andro/63593514#63593514) – Botje Nov 24 '20 at 15:16

1 Answers1

0

On the C++ side, use pipe(2) to create a pair of file descriptors. Then just write updates to the write end and close when you are done.

On the Java side, take the file descriptor of the read end (eg pass it by JNI). Let Java open an InputStream on /dev/fd/X and read until EOF in a separate thread.

Botje
  • 26,269
  • 3
  • 31
  • 41