From f4fd1831daf200a27db75dfe36f23b7e9a9f2085 Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Tue, 16 Apr 2019 07:23:05 -0700 Subject: [PATCH] Fabric: `RNWrapManagedObject` and `RNUnwrapManagedObject` helpers Summary: We use this pattern already and seems we use it more. Those two functions introduce a "semantical" wrappers for this context, so now there is no need to think which exact `__bridge ***` qualifier we should use, so it's much less error-prone. Reviewed By: JoshuaGross Differential Revision: D14896800 fbshipit-source-id: 85b86bfcefdad5aff0375e7172769df86c001506 --- React/Fabric/RCTConversions.h | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/React/Fabric/RCTConversions.h b/React/Fabric/RCTConversions.h index 12f2aa483..0c5596889 100644 --- a/React/Fabric/RCTConversions.h +++ b/React/Fabric/RCTConversions.h @@ -16,6 +16,27 @@ NS_ASSUME_NONNULL_BEGIN +/* + * `RNWrapManagedObject` and `RNUnwrapManagedObject` are wrapper functions that convert ARC-managed objects into + * `std::shared_ptr` and vice-versa. It's a very useful mechanism when we need to pass Objective-C objects through + * pure C++ code, pass blocks into C++ lambdas, and so on. + * + * The idea behind this mechanism is quite simple but tricky: When we instantiate a C++ shared pointer for a managed + * object, we practically call `CFRetain` for it once and then we represent this single retaining operation as a counter + * inside the shared pointer; when the counter became zero, we call `CFRelease` on the object. In this model, one bump + * of ARC-managed counter is represented as multiple bumps of C++ counter, so we can have multiple counters for the same + * object that form some kind of counters tree. + */ +inline std::shared_ptr RNWrapManagedObject(id object) +{ + return std::shared_ptr((__bridge_retained void *)object, CFRelease); +} + +inline id RNUnwrapManagedObject(std::shared_ptr const &object) +{ + return (__bridge id)object.get(); +} + inline NSString *RCTNSStringFromString(const std::string &string, const NSStringEncoding &encoding = NSUTF8StringEncoding) { return [NSString stringWithCString:string.c_str() encoding:encoding]; }