Mrb83
Mrb83

Reputation: 130

Does CFBridgingRelease restore ownership to preexisting references without direct assignment?

If I have the following code:

// objective C++ code .mm
id<MTLTexture> texture = ...;
void* ptr = (void*)CFBridgingRetain(texture);
share_ptr_with_native_code(ptr);
[texture do_stuff]; // is this valid?

// native code .cpp
void share_ptr_with_native(void* ptr)
{
  ptr->do_stuff();
  CFBridgingRelease(ptr);
}

Will texture be valid and retained by ARC again after the call to share_ptr_with_native()?

Upvotes: 0

Views: 128

Answers (2)

Maik
Maik

Reputation: 93

Even everything said is right, it would be nicer if you change your

CFBridgingRelease(ptr);

to

CFRelease(ptr) .

__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are responsible for calling CFRelease or a related function to relinquish ownership of the object.

Taken from https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFDesignConcepts/Articles/tollFreeBridgedTypes.html.

Upvotes: 2

Ken Thomases
Ken Thomases

Reputation: 90671

Other than various errors in your code snippet, yes, the line in question is valid. ARC continues to maintain its own strong reference to object while it's still in use in the top code, in addition to the one that you become responsible for. CFBridgingRetain() has a +1 effect on the retain count of the object, hence "retain" in its name.

Upvotes: 2

Related Questions