Define/Instantiate a java object from c/c++

流过昼夜 提交于 2019-12-22 10:49:24

问题


I a code in java that looks like the following:

class MyClass
{
public void MyFunc(ISomeListener listener);
}

I want to call this method from a c++ program and pass to it the required parameter. Note that the parameter is an implementation of an interface. Thus I need to define AND create java object from c++ and pass it to the method. How can I do this?

P.S. If it helps, the original problem is that the java program is an interface to a hardware (like a driver). I'm trying to create a DLL from this java code so that it can be used in any language. So I thought I'd wrap the code using C/C++ and then make a DLL out of that.


回答1:


I managed to solve the problem by defining the Listener class in java. The listener has a native method with the desired callback signature.

public class MyImpl implements MyInterface
{
  @override
  public native int callback(int i);
}

Compiled this using javac. Then using javah to produce the function declaration to be used with JNI. In the C program I defined the function and loaded Impl class and registered callback into it using RegisterNatives.

P.S. The question of how to actually define a class using JNI remains unanswered.

EDIT:
There's a downside to using this method. I will have to register callbacks in class scope not object scope.



来源:https://stackoverflow.com/questions/15925000/define-instantiate-a-java-object-from-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!