的Andr​​oid NDK,保持住C ++对象对象、Andr、oid、NDK

2023-09-06 00:21:16 作者:進擊的Ladies

我有以下问题。我想写一个Android应用程序,它使用我的遗产C ++类。我必须保持一个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 需要它,你也可以得到它,距离NDK部分采用直接设置它的 SetLongField 和 GetLongField 方法:这允许Java PTR 变量只能从NDK的一部分进行管理的code,我觉得更安全,更易于管理。

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.