简体   繁体   中英

__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:

#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++.

My question is:

What is the affect of adding __bridge in this macro when compiled for Objective-C++? 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.

Is there any issues with the class? It will be used in a single project from both Objective-C and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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