与 c++ 共享内存分配和JNI
我正在用 Java 为 C++ 程序编写一个包装器。包装器是使用 SWIG 完成的。我有以下问题:当我从 Java 调用一个在 C++ 中创建大对象的函数时,Java 不会“看到”它已经分配了大量内存,因为它没有在 Java 堆中分配。问题是,当对象被删除时,垃圾收集器不会被调用,因为 Java 端有足够的可用内存。我尝试的是实现此处描述的内容: http://www.swig .org/Doc1.3/Java.html#java_heap_allocations。这个想法是在Java的堆中为C++分配内存空间。由于我不想对每个 new 都使用它,因此我已重命名了 new 和 delete 并从我的 C++ 代码中显式使用它们,其中需要。
这种机制似乎有效(我可以看到 Java 的堆在垃圾收集器的作用下不断增长和收缩),但不幸的是,我在 memcpy
期间发生了随机崩溃。
如果我手动调用垃圾收集器,我的程序可以运行,但这不是一个非常干净的方法。
感谢您提供任何线索。
I'm writing a wrapper in Java for a C++ program. The wrapper is done using SWIG. I have the following problem: when I call a function from Java which create a big object in C++, Java doesn't "see" that it has allocated a lot of memory since it's not allocated in Java's heap. The problem is that the garbage collector is not called when the object is deleted as from Java side there is plenty of free memory. What I have tried is to implement what is described here: http://www.swig.org/Doc1.3/Java.html#java_heap_allocations. The idea is to allocate memory space for C++ in Java's heap. As I'm not interested to use that for every new
, I have renamed the new
and delete
and use them explicitly from my C++ code where needed.
This mechanism seems to work (I can see in that Java's heap is growing and shrinked by the garbage collector) but unfortunately I have a random crash whis seems to occur during a memcpy
.
If I invoke the garbage collector manually my program is working but it's not a very clean method.
Thanks for any clue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上我没有注意到 swig 网站中的以下行:
这似乎已经解决了问题
In fact I didn't notice the following line in swig website:
This seems to have solved the problem
您不能简单地通过 SWIG 手动调用 C++ 对象析构函数吗?这似乎对我有用。
Couldn't you simply manually invoke the C++ object destructor via SWIG? This seems to work for me.