JNI在C调用不同的VS C ++? [英] JNI Calls different in C vs C++?
问题描述
所以我必须用C以下code,它利用Java本地接口但是我想将其转换为C ++,但我不知道如何。
So i have the following code in C that utilizes Java Native Interface however i would like to convert this to C++ but am not sure how.
#include <jni.h>
#include <stdio.h>
#include "InstanceMethodCall.h"
JNIEXPORT void JNICALL
Java_InstanceMethodCall_nativeMethod(JNIEnv *env, jobject obj)
{
jclass cls = (*env)->GetObjectClass(env, obj);
jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "()V");
if (mid == NULL) {
return; /* method not found */
}
printf("In C\n");
(*env)->CallVoidMethod(env, obj, mid);
}
Java的程序:
Java Program:
class InstanceMethodCall {
private native void nativeMethod();
private void callback() {
System.out.println("In Java");
}
public static void main(String args[]) {
InstanceMethodCall c = new InstanceMethodCall();
c.nativeMethod();
}
static {
System.loadLibrary("InstanceMethodCall");
}
}
什么是其中JNI相互作用的差异与C和C ++?任何帮助是极大的AP preciated。
What are the differences in which JNI interacts with C and C++? Any help is greatly appreciated.
谢谢,皮特
推荐答案
我曾经有书基本JNI 。虽然它有点过时,其中大部分是今天仍然有效。
I used to have the book Essential JNI. And while it is kinda dated, much of it still works today.
如果我没有记错,在C,Java的结构是简单的指针。因此,在你的code,(* ENV) - GT;
被取消引用指针给你访问底层方法
If I recall correctly, in C, Java constructs are simply pointers. Thus, in your code, "(*env)->
" is dereferencing pointers to give you access to the underlying methods.
对于C ++, ENV
,实际上是一个对象 - 一个不同的实体C指针。 (和JNI实际上可以为你的C提供实物++ code来操作,因为C ++实际上支持的对象。)因此, env-&GT;
具有不同的含义C ++,它意味着调用包含在该对象的方法指向 ENV
For C++, "env
" is actually an object - a different entity than a C pointer. (And JNI can actually provide real objects for your C++ code to manipulate, since C++ actually supports objects.) So "env->
" has a different meaning in C++, it means "call the method that is contained in the object pointed to by "env
".
另外一个区别,我相信是很多的C-JNI函数需要你的参数之一是的JNIEnv * ENV
。因此,在c您可能不得不说(* ENV) - GT;富(ENV,吧)
。用c ++,第二次提到的 ENV
是没有必要的,这样你就可以代替说 env-&GT;富(巴)
The other difference, I believe, is that many of the C-JNI functions require that one of your parameters be the "JNIEnv *env
". So in C you might have to say (*env)->foo(env, bar)
. With c++, the second reference to "env
" is not necessary, so you can instead say "env->foo(bar)
"
不幸的是,我没有上面的书在我面前,所以我不能完全证实了这一点!但我认为,调查这两件事情(专找他们对谷歌或其他JNI code)将让你pretty远。
Unfortunately, I don't have the above book in front of me, so I can't quite confirm this! But I think investigating those two things (specifically looking for them on google or in other JNI code) will get you pretty far.
这篇关于JNI在C调用不同的VS C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!