为构造函数创建java本地方法
我正在用 Java 编写一个程序,我想为用 C++ 编写的库创建一个本机接口。但我对如何为构造函数编写本机方法声明感到困惑。
假设我有这个 C++ 类和构造函数:
template <class _Tp,class _Val>
class Arbitrator
{
public:
Arbitrator();
}
我将如何编写本机方法声明?
这就是我到目前为止正在做的事情: 包 hbot.proxy.bwsal.仲裁器;
public class Arbitrator<Tp, Val>
{
public native Arbitrator Arbitrator();
}
我会这样做吗?
谢谢
I am writing a program in Java and I would like to create a native interface for a library written in C++. But I am confused with how to write a native method declaration for a constructor.
Say I have this C++ class and constructor:
template <class _Tp,class _Val>
class Arbitrator
{
public:
Arbitrator();
}
How would I write a native method declaration?
This is what I'm doing so far:
package hbot.proxy.bwsal.arbitrator;
public class Arbitrator<Tp, Val>
{
public native Arbitrator Arbitrator();
}
Is this how I would do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建本机方法。例如,
private native void init()
。从 Java 的构造函数中调用它。在它的 JNI 实现中,根据需要访问 C++ 类。无论如何,您都必须使用 JNI 生成的方法签名,因此如果您想要这样做,则无法将 Java 类直接映射到 C++ 类。
Create native method. For example,
private native void init()
. Call it from constructor in Java. In it's JNI implementation access C++ class as needed.You will have to use JNI generated method signatures anyway, so you can't map directly Java class to C++ class if that's what you wanted to do.
为了从 C++ JNI 代码调用 Java 类构造函数,您需要在此处使用 JNI 构造函数。假设您在 C++ 函数中使用 JNIEnv 传递了对 JVM 的引用,如下所示:
// 函数声明
void
java_com_hunter_mcmillen_Arbitrator (JNIEnv *env, jobject thiz) {
// 引用具有您的方法的 Java 类
jclass itemClazz = env->FindClass("com/hunter/mcmillen /myjava/myclasses/Arbitrator");
// 引用 java 类中的方法
jmethodID constructor = env->GetMethodID(itemClazz, "", "(Ljava/lang/Object;Ljava/lang/Object)V");
}
现在您实际上可以在 C++ 代码中调用构造函数。
In order to call a Java class constructor from C++ JNI code, you need to use JNI constructs here. Assuming you have passed a reference to the JVM with JNIEnv in your C++ function like this:
// Function declaration
void
Java_com_hunter_mcmillen_Arbitrator (JNIEnv *env, jobject thiz) {
// Reference to the Java class that has your method
jclass itemClazz = env->FindClass("com/hunter/mcmillen/myjava/myclasses/Arbitrator");
// Reference to the method in your java class
jmethodID constructor = env->GetMethodID(itemClazz, "<init>", "(Ljava/lang/Object;Ljava/lang/Object)V");
}
And now you can actually call the constructor function in your C++ code.