与 c++ 共享内存分配和JNI

发布于 2024-12-19 16:29:02 字数 571 浏览 0 评论 0原文

我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木落 2024-12-26 16:29:02

事实上我没有注意到 swig 网站中的以下行:

如果您要使用通过 gcc 打开的优化(例如 -O2),请确保您还使用 -fno-strict-aliasing 进行编译

这似乎已经解决了问题

In fact I didn't notice the following line in swig website:

If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing

This seems to have solved the problem

2024-12-26 16:29:02

您不能简单地通过 SWIG 手动调用 C++ 对象析构函数吗?这似乎对我有用。

Couldn't you simply manually invoke the C++ object destructor via SWIG? This seems to work for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文