Using C++ Shared Pointer in swift

Sample C++ class :

class sample {
public:
sample(std::shared_ptr data);
int read_data();
void write_data(int data);
private:
std::shared_ptr m_data;
};

Now I want to create an object of this class in swift file. To do that I have to pass a shared_ptr object during constructor call. How I can achieve that in swift file ?

Thanks

presuming your std::shared_ptr refers to a concrete specialized class template then this kind of class can be used in Swift. Can you try something like :

inline std::shared_ptr<int> makeSharedData() {
  return std::make_shared< int>();
}

class sample {
public:
sample(std::shared_ptr<int> data);
int read_data();
void write_data(int data);
private:
std::shared_ptr<int> m_data;
};

and then in Swift:

let s = sample(makeSharedData())

This is not working. I am getting below build error

std::__1::__shared_ptr_emplace<int, std::__1::allocator>::~__shared_ptr_emplace(), referenced from:
vtable for std::__1::__shared_ptr_emplace<int, std::__1::allocator> in TestFile.o
std::__1::__shared_ptr_emplace<int, std::__1::allocator>::~__shared_ptr_emplace(), referenced from:
vtable for std::__1::__shared_ptr_emplace<int, std::__1::allocator> in TestFile.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

TestFile is my swift file name.

@zoecarver do you think this could be a missing traversal with GenClangDecl?

Thanks for letting us know. Could you please file an issue on GitHub - apple/swift: The Swift Programming Language and attach the header file and the Swift source file with your sources that produces the compilation error?

1 Like

I have created a bug on the github link provided.
Link to the bug : shared_ptr object creation is not working between swift/c++ interoperability. · Issue #67355 · apple/swift · GitHub

1 Like