防止垃圾过早收集 [英] Prevent premature garbage collection
问题描述
我有一个过早的垃圾收集问题.我在SWIG文档中找到了很好的解决方案来解决此类问题问题.但是我遇到了问题,因为我有静态工厂方法,从该方法无法访问非静态参考字段.
I have an issues with premature garbage collection. I've found a nice solution in SWIG documentation for solving such kind of issues. But I've faced with problem since I have static factory method from which non-static reference field can't be accessible.
在下面的C ++代码中应用推荐的SWIG解决方案
Applying recommended SWIG solution to C++ code below
struct Child {
};
struct Parent {
static Parent* create(Child& child);
};
获取像
public static Parent create(Child child) {
long cPtr = SampleJNI.Parent_create(getCPtrAndAddReference(child), child);
return (cPtr == 0) ? null : new Parent(cPtr, false);
}
此代码已损坏,因为Parent.create(Child child)
是静态的,但Parent.getCPtrAndAddReference(Child child)
不是静态的.我正在考虑以下两种解决方案之一.
This code is broken since Parent.create(Child child)
is static but Parent.getCPtrAndAddReference(Child child)
is not. I'm thinking about one of two solutions.
第一个是找到生成类似内容的方法
The first one is find the way to generate something like
public static Parent create(Child child) {
long cPtr = SampleJNI.Parent_create(Child.getCPtr(child), child);
return (cPtr == 0) ? null : new Parent(cPtr, false, child)/* call of alternative constructor created with typmap(javabody) */;
}
但我不知道该怎么做.
第二个解决方案是通过SetObjectField
调用在JNI端实现工具分配.我确实知道一般如何做,但是如果可能的话,我宁愿选择第一个解决方案.
The second one solution is implement assignment on JNI side with SetObjectField
call. I do know how to do it in general but I'd rather prefer the first solution if possible.
推荐答案
尝试如下操作:
%newobject Parent::create;
%typemap(javacode) Parent %{
private Child childReference;
%}
%typemap(javaout) Parent* create(Child&) {
long cPtr = $jnicall;
if (cPtr == 0) {
return null;
} else {
Parent p = new Parent(cPtr, $owner);
p.childReference=child;
return p;
}
}
这会将字段添加到Parent
中,该字段将存储对子项的引用,并在创建时保存引用.
This will add field to Parent
that will store reference to child, and save reference at point of creating.
%newobject
说Java垃圾回收该项目时删除C对象.不要忘记它,否则您将发生内存泄漏.
%newobject
says java to delete C object when garbage collecting this item. Don't forget about it, or you will have memory leaks.
这篇关于防止垃圾过早收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!