JNI双向调用(Java调C++/C++调JAVA)

本文详细介绍了在Android环境中,如何在C++动态库中获取JavaVM和JNIEnv,以及如何实现JAVA调用C++和C++调用JAVA的交互。主要方法包括通过JNI_OnLoad获取JavaVM,以及在Java中声明并调用C++的native方法传递AssetManager。同时,文章引用了StackOverflow上的解答和官方文档作为参考资料。

C++调JAVA

JAVA调C++

获取JavaVm和JNIenv

如何在一个android进程的动态库C++里获取到JavaVM:

1、参考:Get JavaVM and AAssetManager in native c++ Android Library - Stack Overflow

If you want to cover both cases in the same way ("typical" and "native" app) - the only way is next:

  • Add MyLibrary.java to your library. That file should declare native method MyLibrary.init(AssetManager am);. Implementation of that method must be placed in your C++ code, where you get java reference to asset manager and then can obtain AAssetManager *
  • Add JNI_OnLoad() to your library in order to obtain JavaVM*
  • Build your library as separate .so to allow system to invoke your JNI_OnLoad()

Usage looks next:

  • Client app declares custom Application class in its manifest
  • Implementation of this custom class overrides onAttachBaseContext() method, which implementation invokes System.loadLibrary("mylibrary") and then your MyLibrary.init(getAssets()).

2、通过java调用jni时传下来的JNIEnv

How to get a reference to the JVM from a native android executable? - Stack Overflow

官网:

Android JNI学习(三)——Java与Native相互调用 - 简书

https://github.com/android/ndk-samples/tree/main/hello-jni

https://github.com/android/ndk-samples/tree/main/hello-jniCallback

gni官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值