Storing Different Types of Swift Objects in C++ Using New Interop

Hello Everyone,

I'm working on an app that utilizes the new C++ - Swift interop feature. I have a module called ModuleA that contains multiple Swift classes, and I need to store instances of these classes in a C++ class as a class member(to ensure ARC until the class object is deallocated). However, I want to retain the Swift class objects on the stack without directly allocating heap memory from C++.

Sample Swift Code:

public class SwiftClassA {
    public init() {}

    public func FuncA() -> Void {
        // Perform operations specific to SwiftClassA    }
}
 public class SwiftClassB {
    public init() {}

    public func FuncA() -> Void {
        // Perform operations specific to SwiftClassB
    }
}

// Additional Swift classes (SwiftClassC to SwiftClassN) follow a similar structure.

Sample Cpp Code:

CppClass.hpp

#include "ModuleA-Swift.h" // Include generated Swift headerclass

CppClass {

 public:
    // Functions and declarationsprivate:
        XYZ vClassObject; // Placeholder for Any Swift class object
};

CppClass.cpp

#include "ModuleA-Swift.h" // Include generated Swift headervoid

CppClass::SomeFuncA() noexcept
{

    ModuleA::SwiftClassA obj = ModuleA::SwiftClassA::init(); // Initialize SwiftClassA object
 vClassObject = obj; // Assign SwiftClassA object to vClassObject

}
 void CppClass::SomeFuncB() noexcept {
    ModuleA::SwiftClassB obj = ModuleA::SwiftClassB::init(); // Initialize SwiftClassB object
    vClassObject = obj; // How do I Assign SwiftClassB object to vClassObject?
}

I'm looking for suggestions on how to efficiently store different types of Swift class objects in my C++ class while maintaining stack-based object retention and proper memory management. Any help or insights would be greatly appreciated.

Thanks,

Harshal

This is not possible at the time of writing this post. If you really want to do something like this, you need to hold a void pointer by creating an "unmanaged" reference and manually increasing the ARC as per my last interaction with DTS paid support, if anyone finds something new, please feel free to share it here and if you want to understand more on how I achieved it feel free to contact me :)

Thanks :slight_smile:
Harshal

Out of curiosity- can you work with void*/Unmanaged and cast from- and to- Swift types inside C++, or does all of that need to happen inside Swift?

In other words;

void test(void* myUnsafeSwiftClass) {
  // TODO: convert void* to MySwiftClass in C++??
}