gpt4 book ai didi

java - 热衷于摆脱 swig 包装器中的内存分配/释放?

转载 作者:行者123 更新时间:2023-12-02 08:33:02 25 4
gpt4 key购买 nike

我想使用 swig 为复杂对象生成只读包装器。当我读取它时,我想要包装的对象将始终存在。而且我只会在该对象存在时使用我的包装器,因此我不需要 SWIG 的任何内存管理。

对于以下 swig 接口(interface):

%module test

%immutable;
%inline

%{
struct Foo
{
int a;
};

struct Bar
{
int b;
Foo f;
};
%}

我将有一个包装器,它在生成的接口(interface)中会有很多垃圾,并做无用的工作,这会降低我的情况下的性能。
为 Bar 类生成的 java 包装器将如下所示:

public class Bar {
private long swigCPtr;
protected boolean swigCMemOwn;

protected Bar(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}

protected static long getCPtr(Bar obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}

protected void finalize() {
delete();
}

public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
testJNI.delete_Bar(swigCPtr);
}
swigCPtr = 0;
}
}

public int getB() {
return testJNI.Bar_b_get(swigCPtr, this);
}

public Foo getF() {
return new Foo(testJNI.Bar_f_get(swigCPtr, this), true);
}

public Bar() {
this(testJNI.new_Bar(), true);
}

}

我的包装器中不需要“swigCMemOwn”字段,因为它总是错误的。所有与该字段相关的代码也将毫无用处。

原生代码中也存在不必要的逻辑:

SWIGEXPORT jlong JNICALL Java_some_testJNI_Bar_1f_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) {
jlong jresult = 0 ;
struct Bar *arg1 = (struct Bar *) 0 ;
Foo result;

(void)jenv;
(void)jcls;
(void)jarg1_;
arg1 = *(struct Bar **)&jarg1;
result = ((arg1)->f);
{
Foo * resultptr = (Foo *) malloc(sizeof(Foo));
memmove(resultptr, &result, sizeof(Foo));
*(Foo **)&jresult = resultptr;
}
return jresult;
}

我不需要这些对 malloc 和 memmove 的调用。

我想强制 swig 解决这两个问题,但不知道如何解决。可能吗?

最佳答案

为此,有必要为结构类型编写自定义类型映射,如下所示:

%typemap(javabody) SWIGTYPE %{
private long swigCPtr;

protected $javaclassname(long cPtr) {
swigCPtr = cPtr;
}
%}

%typemap(jtype, nopgcpp="1") SWIGTYPE * "long"
%typemap(javaout) SWIGTYPE {
long cPtr = $jnicall;
return new $javaclassname(cPtr);
}

%typemap(javaout) SWIGTYPE *, SWIGTYPE [], SWIGTYPE (CLASS::*) {
long cPtr = $jnicall;
return (cPtr == 0) ? null : new $javaclassname(cPtr);
}

%typemap(out) SWIGTYPE %{
*($&1_ltype*)&$result = &$1;
%}

%typemap(javadestruct) SWIGTYPE ""

%typemap(javaclassmodifiers) SWIGTYPE "public final class"
%nodefaultctor;
%nodefaultdtor;
%immutable;

关于java - 热衷于摆脱 swig 包装器中的内存分配/释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2778332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com