JNI:如何处理包装的 C++ 的创建/删除目的
我想包装一个 C++ 对象,以便可以从 Java 访问它。我已经了解如何通过阅读 jni 并在 java 中使用 c++ new'ed 对象。不过,我还没有弄清楚的一件事是如何处理 C++ 对象的创建和删除。当然,我可以引入创建和删除 C++ 对象的本机方法,但这意味着我必须自己处理 Java 中的内存管理...不是很 Javaish。当我的 Java 包装器对象被创建和垃圾收集时,是否有我应该实现的任何本机方法被调用?
I'd like to wrap a C++ object so I can access it from Java. I have understood how to save a reference to my C++ object in my Java wrapper class by reading jni and using c++ new'ed objects in java. One thing I haven't figured out, though, is how to handle the creation and removal of my C++ object. Sure, I can introduce native methods that create and delete my C++ object but that means I have to take care of the memory management myself in Java...not very Javaish. Are there any native methods I should implement that gets called when my Java wrapper object is created and garbage collected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须编写本机方法来创建和销毁 C++ 对象。我知道有 3 种不同的方法可以用 java 调用它们。
实现
public void Finalize()
你的java对象的方法。一旦您的对象完成,垃圾收集器将调用此方法,因此您可以在此处调用 destroy 方法,垃圾收集器将处理所有事情。 Finalize() 有其缺点,它会减慢垃圾收集器的速度,并且会从不同的线程调用等等。编写一个 dispose() 方法并手动管理内存。这由 swing/AWT 用于本机资源。这使您可以控制删除 C++ 对象的时间和位置。您仍然可以实现 Finalize() 来阻止内存泄漏/调试代码。
使用PhantomReference类和 ReferenceQueue 来检查如果您的对象之一被垃圾收集并从那里删除 c++ 对象。这提供了 Finalize() 的替代方法。
You have to write native methods to create and destroy your c++ object. There are 3 different ways I know of how you could call those with java.
Implement the
public void finalize()
method for your java object. The garbage collector will call this method once your object is finalized so you can place the call to the destroy method here and the garbage collector will take care of everything. finalize() has its downsides, it slows the garbage collector down and will be called from a different thread to name a few.write a dispose() method and manage your memory by hand. This is used by swing/AWT for native resources. This gives you control over when and where the c++ object is deleted. You can still implement finalize() to stop memory leaks/debug your code.
Use the PhantomReference class and a ReferenceQueue to check if one of your Objects was garbage collected and delete the c++ object from there. This provides an alternative to finalize().