I tried using function
capnp::writePackedMessageToFd(fd, builder)
to serialize C++ message and send it as packet to the file descriptor. Using the above function in my code gave me runtime Exception.
Code:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include "MapSchema.capnp.h" // Include the generated schema code
#include <capnp/serialize-packed.h>
#include <iostream>
#include <winsock2.h> // Include Winsock for UDP sockets
#include <kj/exception.h>
#pragma comment(lib, "ws2_32.lib") // Link against Winsock library
int main() {
WSADATA wsaData;
unsigned char* buff;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock." << std::endl;
return 1;
}
SOCKET udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (udpSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket." << std::endl;
WSACleanup();
return 1;
}
std::cout << "WSA Success" << std::endl;
sockaddr_in destAddr;
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(12345); destAddr.sin_addr.s_addr =
inet_addr("127.0.0.1");
::capnp::MallocMessageBuilder message;
KeyValueMap::Builder mapBuilder = message.initRoot<keyvaluemap>();
std::cout << "ip Success" << std::endl;
auto entries = mapBuilder.initEntries(2);
entries[0].setKey("key1");
entries[0].setValue("value1");
entries[1].setKey("key2");
entries[1].setValue("value2");
kj::HandleOutputStream out((HANDLE)udpSocket);
std::cout << "soc: " << &out;
capnp::writePackedMessage(out, message);
closesocket(udpSocket);
WSACleanup();
return 0;
}
Exception:
Unhandled exception at 0x76D5D9502 in file.exception Microsoft C++ exception: kj::ExceptionImp at memory location 0x0102D4D8
What I have tried:
Replacing the code snippet:
kj::HandleOutputStream out((HANDLE)udpSocket);
std::cout << "soc: " << &out;
capnp::writePackedMessage(out, message);
with this:
auto serializedMessage = capnp::messageToFlatArray(message);
const char* buffer = serializedMessage.asChars().begin();
int bufferLength = serializedMessage.asChars().size();
buff = const_cast<unsigned char*="">(reinterpret_cast<const unsigned="" char*="">(buffer));
int result = sendto(udpSocket, buffer, bufferLength, 0,
(sockaddr*)&destAddr, sizeof(destAddr));
if (result == SOCKET_ERROR) {
std::cerr << "Failed to send data: " << WSAGetLastError() << std::endl;
}
Solved the exception, so does that mean
capnp::writePackedMessageToFd(fd, builder)
cannot be used in Windows to send the serialized data directly to file descriptor?