强制Java调用我的C ++析构函数(JNI) [英] Force Java to call my C++ destructor (JNI)

查看:636
本文介绍了强制Java调用我的C ++析构函数(JNI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个问题以前会被问过,但我在这里找不到...

I thought this question would have been asked before, but I couldn't find it here...

我使用SWIG创建一个JNI包装器一个C ++类。所有的工作伟大的,除了Java从来没有似乎调用类的finalize(),所以,反过来,我的类的析构函数从来没有被调用。类的析构函数做了一些最终的文件I / O,所以不幸的是,这不只是一个小的内存泄漏。

I've used SWIG to create a JNI wrapper around a C++ class. All works great except that Java never seems to call the class's finalize(), so, in turn, my class's destructor never gets called. The class's destructor does some final file I/O, so unfortunately, this isn't just a minor memory leak.

通过Google搜索,似乎没有一种强制Java到GC并销毁对象的方法。真的?

Searching through Google, there doesn't seem to be a way to force Java to GC and destroy an object. True?

我知道我可以操纵我的SWIG文件并创建一个调用C ++析构函数的java函数,但是这个类被最终用户在几个不同的平台/

I know I could manipulate my SWIG file and create a java function that would call the C++ destructor, but this class is used by end users in several different platforms/languages, so the addition of a Java-only will create an inconsistency that our tech writers aren't going to like.

推荐答案

添加一个仅限Java的方法会导致我们的技术作者不喜欢。你不能强制GC与System.gc()。
也不能保证将会有一个GC运行,例如,如果你的应用程序只运行一段时间,然后你的终结器根本不会运行(JVM不会运行它在退出时)。你应该为你的类创建一个close()或者destroy()或者其他的函数,当你完成使用这个类的实例时,最好是从finally块中调用它。

You can't force GC with System.gc(). Also it is not guaranteed that there will ever be a GC run for example if your app runs only for a short time and then your finalizer won't run at all (the JVM does not run it when exiting). You should create a close() or destroy() or whatever function for your class and when you finished using an instance of this class call it, preferably from a finally block, like.


MyClass x = null;
try{
    x = new MyClass();
    x.work();
} finally {
    if (x!=null)
        x.close();
}

这篇关于强制Java调用我的C ++析构函数(JNI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆