【发布时间】:2014-01-11 22:47:35
【问题描述】:
我在 Ubuntu 中使用 SWIG 2.0.10 在 Java 中调用 C++ 代码。
我的 C++ 代码是:
//ImgPro.h:
#include <vector>
typedef struct _bin
{
char* name;
float value;
} Bin;
typedef struct imgprops
{
std::vector<Bin> color;
int width;
int height;
char *print;
} ImageProperties;
class ImgPro
{
public:
ImgPro();
ImageProperties *processImage(char* imagePath);
};
processImage函数定义为:
ImageProperties* ImgPro::processImage(char *imagePath)
{
ImageProperties* imgProp = new ImageProperties();
imgProp->width = 200;
imgProp->height = 200;
char* fp = new char(5);
strcpy(fp, "abc!");
imgProp->print = fp;
Bin outputBin1;
char *name1 = new char(strlen("red")+1);
strcpy(name1, "red");
outputBin1.name = name1;
outputBin1.value = 0.125;
Bin outputBin2;
char *name2 = new char(strlen("blue")+1);
strcpy(name2, "blue");
outputBin2.name = name1;
outputBin2.value = 0.27;
vector<Bin> tempVec;
tempVec.push_back(outputBin1);
tempVec.push_back(outputBin2);
imgProp->color = tempVec;
return imgProp;
}
所以,为了使用 swig 生成 jni 代码,我使用了以下 swig 文件(注意:vector.i 文件是使用此 example 创建的):
%module CBIR
// to handle char** has String_Array in Java
%include <various.i>
%include "vector.i"
%{
#include "ImgPro.h"
%}
// to handle char** has String_Array in Java
%apply char **STRING_ARRAY { char ** };
// memory release
%extend imgprops {
~imgprops(){
if($self != NULL)
{
// releasing print element
if($self->print != NULL)
delete[] $self->print;
// releasing vector elements
for(uint x = 0; x < $self->color.size(); x++)
{
Bin currentBin = $self->color[x];
if(currentBin.name != NULL)
delete[] currentBin.name;
}
// releasing stuct Pointer
delete $self;
}
}
}
%include "ImgPro.h"
%template(BinVec) std::vector<Bin>;
这会在 swig_wrap 文件中生成下一个函数:
SWIGINTERN void delete_imgprops(imgprops *self){
if(self != NULL)
{
// releasing print element
if(self->print != NULL)
delete[] self->print;
// releasing vector elements
for(uint x = 0; x < self->color.size(); x++)
{
Bin currentBin = self->color[x];
if(currentBin.name != NULL)
delete[] currentBin.name;
}
// releasing stuct Pointer
delete self;
}
}
在删除 ImageProperties c++ 函数中调用。
但是,在 Java 中运行以下代码永远不会释放在 C++ 中分配的内存(调用函数 delete_imgprops):
ImgPro imgObject = new ImgPro();
ImageProperties propObject = imgObject.processImage("imagem123-jpg");
int width = propObject.getWidth();
int height = propObject.getHeight();
String fingerPrint = propObject.getPrint();
propObject.delete();
imgObject.delete();
所以,在分析了代码流之后,我找到了内存没有释放的原因。 SWIG 生成的 ImageProperties.Java 文件包含删除函数等:
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CBIRJNI.delete_ImageProperties(swigCPtr);
}
swigCPtr = 0;
}
}
“CBIRJNI.delete_ImageProperties(swigCPtr);”行永远不会调用,因为 var swigCMemOwn 始终为假。
我明白因为Java端不分配内存所以它也不会释放它,那么我该怎么做才能确保java释放内存而不对swig生成的java文件进行任何修改?
我发现释放内存的解决方案是在 delete() 函数上注释 if(swigCMemOwn) 测试,但我认为这不是最好的方法!
谢谢,塞尔吉奥
【问题讨论】:
标签: java c++ memory-leaks swig