简体   繁体   English

从Java到第三方C ++库的JNI回调系统

[英]JNI callback system from Java to a 3rd party C++ lib

I've done some research, including here in StackOverflow, but I still have some issues to deal and I kind of need your help. 我已经进行了一些研究,包括StackOverflow中的此处,但仍然有一些问题需要解决,我需要您的帮助。

So, I have a Java lib that's used as wrapper to a 3rd party C++ lib. 因此,我有一个Java库,用作第三方C ++库的包装。 This C++ lib is where all the logic is. 这个C ++库是所有逻辑所在。 So, it has an asynchronous behaviour and there's the need to register callbacks to get notified for its events. 因此,它具有异步行为,因此需要注册回调以获取有关其事件的通知。 I want to be able to register callbacks from Java and to be able to get notified of their respective events in Java. 我希望能够从Java中注册回调,并能够在Java中获得有关其各自事件的通知。

Currently I have something like this: 目前我有这样的事情:

  1. A Java method to register a callback (this callback is registered in Java) and to call a C++ "native" method that will register a callback in the 3rd party lib (this is done via C++); 一种Java方法,用于注册回调(此回调在Java中注册)并调用C ++“本地”方法,该方法将在第三方lib中注册回调(这是通过C ++完成);
  2. Another Java method, named something like "fireMyEvent", to be called by my 3rd party's lib callback (from C++). 我的第三方的lib回调(来自C ++)调用另一个Java方法,命名为“ fireMyEvent”。

The problem here is that when my 3rd party's lib callback is fired I don't have access to the JNIEnv, nor to the jobject. 这里的问题是,当我的第三方的lib回调被触发时,我无权访问JNIEnv或Jobject。

I've seen here at StackOverflow how to access the JNIEnv pointer by caching a JavaVM pointer. 我在StackOverflow上看到了如何通过缓存JavaVM指针来访问JNIEnv指针。 Nevertheless, I'm not sure how to access the jobject instance, to be able to call my CallVoidMethod: 不过,我不确定如何访问jobject实例,以便能够调用我的CallVoidMethod:

env->CallVoidMethod(theJObjectThatIWant, methodId, ...)

I though about caching the jobject during the call to the C++ method that registers the callback in my 3rd party lib, but I'm not sure if this is acceptable in a scenario where there are more than one "Java wrapper objects" (I'm referring to the object that wraps the C++ functionality through JNI) in an application. 我虽然打算在调用C ++方法期间将Jobject缓存在我的第三方库中,但我不确定在有多个“ Java包装对象”的情况下这是否可以接受(我m指的是在应用程序中通过JNI包装C ++功能的对象。

What are your suggestions to overcome this situation? 您对克服这种情况有何建议?

I hope I've made made my problem clear and I apologize if my research wasn't good enough to find an already existing answer in this forum :(. 我希望我已经弄清楚了我的问题,如果我的研究不够好,无法在该论坛中找到已经存在的答案,我深表歉意。

Many thanks and regards. 非常感谢和问候。

Edit : Caching the " jobject " doesn't seem to be working, because I end up having an "Access violation" executing the " CallVoidMethod " method. 编辑 :缓存“ jobject ”似乎不起作用,因为我最终遇到了执行“ CallVoidMethod ”方法的“访问冲突”。

To cache a Java reference beyond the end of a native call, a global reference is required. 要在本机调用结束后缓存Java参考,则需要全局参考。

See "Local and global references" in this JNI reference . 请参阅此JNI参考中的“本地和全局参考”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM