Objective-C 垃圾收集和 C++

发布于 2025-01-05 20:24:25 字数 432 浏览 4 评论 0原文

我正在用 Objective-C 编写一个启用垃圾收集的程序。它依赖于某个第三方 C++ 库,但它的标头不能编译为 Objective-C++,因此我有大量纯 C++ 代码,其中一些 Objective-C++ 弥补了这一差距。

我在桥中做了这样的事情,以允许将 Objective-C 对象传递给 C++:

#ifdef __OBJC__
  @class NSManagedObjectID;
#else
  typedef void NSManagedObjectID;
#endif

我的猜测是这不是正确的做法,因为 C++ 对 Objective-C 的垃圾收集一无所知。如果 C++ 端保留了一个引用(我希望它保留),而 Objective-C 端没有任何引用,那么我最终会得到一个悬空指针吗?

如果是这样,处理这个问题的正确方法是什么?

I'm writing a program in Objective-C with garbage collection enabled. It relies on a certain third party C++ library, but its headers don't compile as Objective-C++ so I have a good amount of pure C++ code with some Objective-C++ bridging the gap.

I did this sort of thing in the bridge, to allow passing Objective-C objects to C++:

#ifdef __OBJC__
  @class NSManagedObjectID;
#else
  typedef void NSManagedObjectID;
#endif

My guess is that this is not the right thing to do, as C++ knows nothing of Objective-C's garbage collection. If the C++ side holds onto a reference (and I'd like it to) while nothing on the Objective-C side does, would I end up with a dangling pointer?

If so, what's the right way to deal with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

抽个烟儿 2025-01-12 20:24:25

因此,当我说“垃圾收集”时,我真的应该说“自动引用计数”。看来我正在寻找的是桥接转换(“需要这些转换才能将对象传入和传出 ARC 控制”):

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.casts

So when I said "garbage collection" I should really have said "automatic reference counting." And it seems that what I'm looking for are bridged casts ("These casts are required in order to transfer objects in and out of ARC control"):

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.casts

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