Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions documentation/cxx-interop/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,35 @@ object.doSomething()
// `object` will be released here.
```

#### Calling conventions when returning Shared Reference Types from C++ to Swift

When C++ functions and methods return `SWIFT_SHARED_REFERENCE` types, it is necessary to specify the ownership of the returned value.
For this you should use the `SWIFT_RETURNS_RETAINED` and `SWIFT_RETURNS_UNRETAINED` annotations on functions and methods.
These annotations tell the Swift compiler whether the type is returned as `+1` (retained) or `+0` (unretained).

```c++
// Returns +1 ownership.
SharedObject* makeOwnedObject() SWIFT_RETURNS_RETAINED;

// Returns +0 ownership.
SharedObject* getUnOwnedObject() SWIFT_RETURNS_UNRETAINED;
```

These annotations are necessary to ensure that appropriate `retain`/`release` operations are inserted at the boundary:

```swift
let owned = makeOwnedObject()
owned.doSomething()
// `owned` is already at +1, so no further retain is needed here

let unOwned = getUnOwnedObject()
// Swift inserts a retain operation on `unowned` here to bring it to +1.
unOwned.doSomething()
```

Note that the Swift compiler will automatically infer the ownership conventons for Swift functions returning `SWIFT_SHARED_REFERENCE` types.
See [Exposing C++ Shared Reference Types back from Swift](#exposing-c-shared-reference-types-back-from-swift) for calling Swift functions returning `SWIFT_SHARED_REFERENCE` types from C++.

### Inheritance and Virtual Member Functions
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: ### -> ####


Similar to value types, casting an instance of a derived reference type to a
Expand Down