从c / c ++定义/实例化一个java对象 [英] Define/Instantiate a java object from c/c++

查看:188
本文介绍了从c / c ++定义/实例化一个java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中的代码如下:

I a code in java that looks like the following:

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

我想从一个c ++程序调用这个方法,参数。注意,该参数是接口的实现。因此,我需要从c ++中定义 AND java java对象,并将其传递给方法。我如何做到这一点?

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?

PS
如果有帮助,原来的问题是java程序是硬件接口。我试图从这个java代码创建一个DLL,以便它可以在任何语言使用。所以我想我会使用C / C ++包装代码,然后制作一个DLL。

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.

推荐答案

通过在java中定义Listener类来解决问题。侦听器具有包含所需回调签名的本地方法。

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);
}

使用javac编译。然后使用javah产生要与JNI一起使用的函数声明。在C程序中,我定义了函数并加载了Impl类并使用 RegisterNatives

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.

PS 如何使用JNI未答复。

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

编辑:

使用此方法有一个缺点。我必须在类范围而不是对象范围中注册回调。


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

这篇关于从c / c ++定义/实例化一个java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆