Android NDK, keeping live C++ objects(Android NDK,保持实时 C++ 对象)
问题描述
我遇到了以下问题.我想编写一个使用我的遗留 C++ 类的 Android 应用程序.我必须在整个应用程序生命周期内保持 C++ 对象处于活动状态.
I've got a following problem. I want to write an Android application, which uses my legacy C++ classes. I have to keep a C++ object alive during the whole application lifetime.
我用 C# 编写了一个类似的应用程序,并通过将指向 C++ 类的指针传递给 C# 并使用 IntPtr 将其存储在那里来解决了这个问题.然后,当我想调用该对象的方法时,我只需将该指针再次传递给 C++,转换为类指针并调用它的方法.
I wrote a similar application in C# and solved the problem by passing a pointer to a C++ class to C# and storing it there using IntPtr. Then, when I wanted to call a method on that object, I simply passed that pointer again to C++, converted to a class pointer and called a method on it.
如何在 Java 和 Android NDK 中获得类似的结果?Java 是否支持存储指针?
How can I achieve similar result in Java and Android NDK? Does Java support storing pointers?
推荐答案
是的,您可以执行与在 C# 中所做的完全相同的操作.
Yes, you can do the exact same than what you did in C#.
创建新的 C++ 对象:
To create your new C++ Object:
jlong
Java_package_name_new(JNIEnv *, jobject) {
return (long)(new CPP_Object());
}
您可以将此方法的返回值存储在 Java ptr
变量中,并将其传递给所有需要它的 NDK 方法:
You can store the return value of this method in a Java ptr
variable, and pass it to all NDK methods that need it:
void
Java_package_name_doSomething(JNIEnv *, jobject, jlong ptr) {
CPP_Object *obj = (CPP_Object *)ptr;
// do whatever you want with the object
}
最后用类似这样的方式删除它:
And finally delete it with something like:
void
Java_package_name_delete(JNIEnv *, jobject, jlong ptr) {
delete (CPP_Object *)(ptr);
}
除了将 ptr
传递给所有需要它的方法,您还可以使用 SetLongField
和 GetLongField<直接从 NDK 部分获取并设置它/code> 方法:这允许仅从代码的 NDK 部分管理 Java
ptr
变量,我发现它更安全且更易于管理.
Instead of passing ptr
to all methods that need it, you can also get it and set it directly from the NDK part using the SetLongField
and GetLongField
methods: this allows the Java ptr
variable to be managed only from the NDK part of the code, which I find safer and easier to manage.
这篇关于Android NDK,保持实时 C++ 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android NDK,保持实时 C++ 对象
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01