Android NDK,保持实时 C++ 对象

时间:2023-01-12
本文介绍了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 传递给所有需要它的方法,您还可以使用 SetLongFieldGetLongField<直接从 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++ 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!