A C++ type passed to a C-style Swift function pointer is freed twice

Hey all!

I'm passing a Swift function as a C-style function pointer to C++, which then calls it later.

This works fine if I pass primitives like double to that Swift function, but for some reason every C++ type with a destructor (eg std::shared_ptr) will destructure twice - which causes memory corruption issues and crashes the app!

Got value from C++: shared_ptr<basic_string<CChar, char_traits<CChar>, allocator<CChar>>>()
SwiftSharedPointerTest(34066,0x1e6e6f840) malloc: Heap corruption detected, free list is damaged at 0x600001726730
*** Incorrect guard value: 7813868916180873059
SwiftSharedPointerTest(34066,0x1e6e6f840) malloc: *** set a breakpoint in malloc_error_break to debug

I've already filed a bug report in the Swift repo (Passing a C++ type to a C-style Swift function crashes: `malloc: Heap corruption detected ***` · Issue #78292 · swiftlang/swift · GitHub), but I'm creating this topic here as discussion in case anyone has any better ideas than what I'm trying to do?
I'm essentially trying to bridge a Swift lambda over to a C++ std::function, and I do this by just wrapping it in a void* that acts as my context/closure, and then unwrap it before each call.

2 Likes