且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-16 08:38:22

是的,你可以做的比你在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.