I'm still testing out swift on windows as an option for porting our codebase to a windows project. I'm successfully building a .dll and calling it for a simple c++ command line app in vs 2019. However, I've run into one problem...
When our swift functions return a char*, we get an access violation exception when trying to free them in the host app. It sounds a lot like this problem:
Here's the swift library:
import CRT
import WinSDK
@_cdecl("printhello")
public func printhello() {
print("Hello World")
}
@_cdecl("hellotext")
public func hellotext() -> UnsafeMutablePointer<Int8>? {
return _strdup("Hello return string")
}
And the cpp host:
#include <iostream>
extern "C" void printhello();
extern "C" const char* hellotext();
int main()
{
printhello();
const char* str = hellotext();
printf("%s\n", str);
free((char*)str); // <- access violation here
return 0;
}
compnerd
(Saleem Abdulrasool)
2
Yeah, this seems likely to be a cross-domain free. I would recommend that you actually create an entry point to expose the free function to the user. Alternatively, you could do the dual call approach (call without a buffer to get the necessary allocation size and then allocate and call again with the buffer to fill in the buffer).
1 Like
Thanks for the confirmation. Both of those are good workarounds.