Hello Everyone,
I have a use case where I wanted to interpret the "Data" object received as a part of my NWConnection's recv call. I have my interpretation logic in cpp so in swift I extract the pointer to the raw bytes from Data and pass it to cpp as a UnsafeMutableRawPointer.
In cpp it is received as a void * where I typecast it to char * to read data byte by byte before framing a response.
I am able to get the pointer of the bytes by using
// Swift Code
// pContent is the received Data
if let content = pContent, !content.isEmpty {
bytes = content.withUnsafeBytes { rawBufferPointer in
guard let buffer = rawBufferPointer.baseAddress else {
// return with null data.
}
// invoke cpp method to interpret data and trigger response.
}
// Cpp Code
void InterpretResponse (void * pDataPointer, int pDataLength) {
char * data = (char *) pDataPointer;
for (int iterator = 0; iterator < pDataLength; ++iterator )
{
std::cout << data<< std::endl;
data++;
}
}
When I pass this buffer to cpp, I am unable to interpret it properly. Can someone help me out here?
Thanks :)
Harshal
That was also posted by me.
Sure. But if you’re gonna ‘forums surf’, it’s only polite to link to your other attempts.
Anyway, with regards your code, I think this is a simply a case of a missing *
. Consider these two C++ files:
-
Test.hpp
:#ifndef Test_hpp #define Test_hpp #include <cstddef> extern void qqqTest(const void * base, size_t len); #endif /* Test_hpp */
-
Test.cpp
:#include "Test.hpp" #include <iostream> extern void qqqTest(const void *base, std::size_t len) { const char * cursor = (const char *) base; for (size_t i = 0; i < len; i++) { std::cout << *cursor << std::endl; cursor++; } }
and this Swift file:
-
main.swift
:import Foundation func main() { let d = Data("Hello Cruel World!".utf8) d.withUnsafeBytes { buf in qqqTest(buf.baseAddress!, buf.count) } } main()
If I put them all into a command-line tool target and run it on my Mac (Xcode 16.0 on macOS 14.6.1), I got this:
H
e
l
l
o
C
r
u
e
l
W
o
r
l
d
!
Note that I’m using *cursor
in the place where your code has just data
.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"