Hello everyone,
I'm encountering an issue with Swift and C++ interoperability when passing a void pointer between Swift and C++ functions. When I pass pMessageBuffer (an UnsafeMutableRawPointer) from Swift to MyCppClass.NFCompletion (a static c++ function), which expects a reference to void pointer, Swift throws an error "Cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'Optional<UnsafeMutableRawPointer>' ".
Here is a sample code to help in better visualization of the usecase.
Cpp Code
class MyCppClass {
public:
static void SendData(void *pMessage, TUInt16 pMessageLength) {
// Assume vSocket is my Swift object held in C++.
vSocket.Send(pMessage, pMessageLength);
}
static void NFCompletion(void * & pBuffer, TInt64 pErrorCode, VPtr pCompletionFunction) {
// Process the buffer.
}
};
Swift Code:
public class MySwiftClass {
var vConnection: NWConnection?
public init() {}
public func Send(_ pMessageBuffer: UnsafeMutableRawPointer, _ pMessageLength: TSUInt16) {
let messageData = Data(bytesNoCopy: pMessageBuffer, count: Int(pMessageLength), deallocator: .none)
self.vConnection?.send(content: messageData, completion: .contentProcessed { nw_error in
var error_code: TSInt64 = 0
if let nw_error = nw_error {
error_code = self.InternalGetNetworkErrorCode(nw_error)
}
// Here's where the issue arises:
MyCppClass.NFCompletion(pMessageBuffer, TInt64(error_code), self.uCompletionHandler)
})
}
// Example function to handle network errors
private func InternalGetNetworkErrorCode(_ error: Error) -> TSInt64 {
// Implementation to convert nw_error to TSInt64 error code
return 0 // Placeholder return value
}
}
Could someone please help me understand why this conversion error occurs? How should I correctly handle passing a void pointer between Swift and C++ functions, ensuring compatibility and proper memory management?
Note: TSInt64 is typealias for swift Int and TInt64 is alias of c++ int_64t.
Thank you in advance for your assistance!
Regards,
Harshal