I am trying to figure out some COM marshalling features. Eventually, I want to persist a deeply nested variant array to file but I am trying first with a simple string. I realise these APIs are meant for remote procedure calls but I was hoping this serialization was also suitable for file persistence.
I work a lot with Excel VBA and to discover this serialization APIs is a real eye opener.
The code below serializes a BSTR to a buffer, the buffer is copied which will serve as a substitute for saving to and loading from a file.
The current problem is the BSTR_UserUnmarshal is throwing an exception Unhandled exception at 0x7631C762 (KernelBase.dll) in RPCMarshalling.exe: 0x00000057: The parameter is incorrect. occurred
I probably have the syntax wrong because I am working with scraps of sample code. The goal is to get the string from srctest to desttest with RPC serialization API calls.
// RPCMarshalling.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
//https://searchcode.com/file/140723732/dlls/oleaut32/tmarshal.c#l-818
typedef struct _marshal_state {
LPBYTE base;
int size;
int curoff;
} marshal_state;
int main()
{
::CoInitialize(0);
CComBSTR srctest("Hello");
marshal_state srcbuf;
memset(&srcbuf, 0, sizeof(srcbuf));
ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
ULONG size = ::BSTR_UserSize(&flags, 0, &srctest);
DWORD newsize = max(size, 256);
(&srcbuf)->base = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newsize);
if (!(&srcbuf)->base)
return E_OUTOFMEMORY;
::BSTR_UserMarshal(&flags, (&srcbuf)->base + (&srcbuf)->curoff, &srctest);
(&srcbuf)->curoff = size;
std::cout << "Hello World!\n" << size << "\n";
marshal_state destbuf;
memset(&destbuf, 0, sizeof(destbuf));
(&destbuf)->base = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newsize);
if (!(&destbuf)->base)
return E_OUTOFMEMORY;
/* pretend we are loading from file saved by src buffer */
RtlCopyMemory((&destbuf)->base, (&srcbuf)->base, newsize);
CComBSTR desttest("");
BSTR deststring;
try
{
unsigned char *buffer;
buffer = ::BSTR_UserUnmarshal(&flags, (&destbuf)->base, &deststring);
}
catch (int e)
{
std::cout << "Error:" << e << "\n" << size << "\n";
}
::CoUninitialize();
}