Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2019-09-06:什么是JNI?具体说说如何实现Java与C++的互调? #142

Open
Moosphan opened this issue Sep 6, 2019 · 5 comments
Labels
Java NDK 底层开发

Comments

@Moosphan
Copy link
Owner

Moosphan commented Sep 6, 2019

PS:可通过代码示例来说明Java与C++的调用过程。

@Moosphan Moosphan added Java NDK 底层开发 labels Sep 6, 2019
@zkHuang
Copy link

zkHuang commented Sep 9, 2019

我是来看答案的。

@715047274
Copy link

The Java Native Interface (JNI) is a standard to integrate in a portable way C++ and Java code. It works in both directions: you can call a C++ library from Java or you can call Java components from C++. In this tutorial, I'll explain the second approach.
How does this work?

  • We first have to find the right class with FindClass(), which acts as a class loader. It will search for an appropriate .class file in the list of directories that was provided at JVM initialization. If the Java class is included in a package, you shall provide its full name.

  • The class is then passed to GetStaticMethod(), which shall find the right method in the class. The last parameter of this function is the most difficult one: the method signature. In case of any mismatch here, the method won't be found. "()" means a function with no parameter and "V" that the return type is void.

  • A static method is independent of any object. So we can then call the method with CallStaticVoidMethod().

@xiongliang120
Copy link

1: java 调用 c++ 方法, 通过 java类定义 native 方法, 使用javah 生成.h 头文件,定义cpp文件实现该方法, java 层就可以直接调用该方法了。
2: c++ 调用java 方法,分静态方法和非静态方法.
静态方法调用
JniHelper::callStaticStringMethod(classPath, "getAppName");
非静态方法调用
JniMethodInfo->CallVoidMethod(jobj,info.methodID,forceLogin);

@aositeluoke
Copy link

  • 在Java类中声明native方法
  • 使用javac命令将Java类生成class文件
  • 使用javah文件生成头文件
  • 编写cpp文件实现jni方法
  • 生成so库
    到此为止,java就可以通过调用native方法调用c++函数了,对于在c++中调用java方法,
  • 通过完整类名获取jclass
  • 根据方法签名和名称获取构造方法id
  • 创建对象(如果要调用的是静态方法则不需要创建对象)
  • 获取对象某方法id
  • 通过JNIEnv根据返回值类型、是否是静态方法调用对应函数即可

@rambowding
Copy link

这篇讲的比较清楚:https://www.jianshu.com/p/921a5142ae12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Java NDK 底层开发
Projects
None yet
Development

No branches or pull requests

6 participants