简体   繁体   English

__bridge强制转换为C ++和Objective-C ++

[英]__bridge casts in C++ & Objective-C++

I'm trying to write a templated C++ wrapper around a block and don't fully understand the affect that __bridge will have in the following code: 我正在尝试在一个块周围编写一个模板化的C ++包装器,并且不完全理解__bridge在以下代码中的影响:

#if defined(__OBJC__)
#define SAFE_BLOCK_COPY(...) ((__bridge __typeof(__VA_ARGS__))Block_copy((__bridge const void *)(__VA_ARGS__)))
#else
#define SAFE_BLOCK_COPY(Arg) Block_copy(Arg)
#endif

template <typename ReturnType, typename... Args>
struct CppBlock<ReturnType(Args...)>
{
    typedef ReturnType (^BlockType)(Args...);

    BlockType block;

    CppBlock(BlockType inBlock) {
        block = SAFE_BLOCK_COPY(inBlock);
    }

    ~CppBlock() {
        Block_release(block);
    }

    ReturnType operator()(Args&&... args) const {
        return block(std::forward<Args>(args)...);
    }
}

I created the SAFE_BLOCK_COPY macro so the class can be used from both C++ & Objective-C++, as __bridge is unavailable to use directly from C++. 我创建了SAFE_BLOCK_COPY宏,因此可以在C ++和Objective-C ++中使用__bridge ,因为__bridge无法直接在C ++中使用。

My question is: 我的问题是:

What is the affect of adding __bridge in this macro when compiled for Objective-C++? 为Objective-C ++编译时,在此宏中添加__bridge什么影响? As far as I understand it, (__bridge T) is essentially equivalent to static_cast<T> as there's no transfer of ownership, so the code generated should be identical whether called from C++ or Objective-C. 据我了解, (__bridge T)本质上等效于static_cast<T>因为没有所有权转移,因此生成的代码无论从C ++还是从Objective-C调用都应该相同。

Is there any issues with the class? 班上有什么问题吗? It will be used in a single project from both Objective-C and C++. 它将在Objective-C和C ++的单个项目中使用。

If the Objective-C is using ARC (and I think you are because bridge casts I believe are only used in ARC), the memory management of Objective-C object pointer types, including block pointer types, is managed by ARC and you shouldn't be calling Block_copy or Block_release on them explicitly. 如果Objective-C使用的是ARC(我认为您是因为我认为桥强制转换仅在ARC中使用),那么Objective-C对象指针类型(包括块指针类型)的内存管理将由ARC管理,您不应不能在其上显式调用Block_copyBlock_release

You should probably do something like this: 您可能应该执行以下操作:

#if defined(__OBJC__)
#define SAFE_BLOCK_COPY(Arg) (Arg)
#else
#define SAFE_BLOCK_COPY(Arg) Block_copy(Arg)
#endif

#if defined(__OBJC__)
#define SAFE_BLOCK_RELEASE(Arg)
#else
#define SAFE_BLOCK_RELEASE(Arg) Block_release(Arg)
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM