Skip to content

Instantly share code, notes, and snippets.

@mbikovitsky
Created May 21, 2016 10:48
Show Gist options
  • Save mbikovitsky/d051200b3aa6ff41cd01908943d2983f to your computer and use it in GitHub Desktop.
Save mbikovitsky/d051200b3aa6ff41cd01908943d2983f to your computer and use it in GitHub Desktop.
MSRPC type serialization sample
interface MyInterface
{
typedef [encode, decode] MY_STRUCT;
}
import "oaidl.idl";
import "ocidl.idl";
[
uuid(c28d202f-e92d-4e53-b272-ae63eb0c97e8),
version(1.0)
]
interface MyInterface
{
typedef struct _MY_STRUCT
{
DWORD dwSomeDword;
} MY_STRUCT, *PMY_STRUCT;
}
#include <Windows.h>
#include <tchar.h>
#include <Rpc.h>
#include <malloc.h>
#include <memory.h>
#include <assert.h>
#include "Interface_h.h"
void __RPC_FAR *
__RPC_USER
midl_user_allocate(
size_t cBytes
)
{
// Buffers must be 8-byte aligned.
return (void __RPC_FAR *)_aligned_malloc(cBytes, 8);
}
void
__RPC_USER
midl_user_free(
void * pBuffer
)
{
_aligned_free(pBuffer);
}
INT
_tmain(VOID)
{
RPC_STATUS eStatus = RPC_E_FAULT;
char * pcEncoded = NULL;
unsigned long cbEncoded = 0;
handle_t hEncoder = NULL;
MY_STRUCT tStruct = { 0x1337 };
handle_t hDecoder = NULL;
MY_STRUCT tDecoded = { 0 };
// Create a dynamic encoding handle. Buffers will be allocated on demand.
eStatus = MesEncodeDynBufferHandleCreate(&pcEncoded, &cbEncoded, &hEncoder);
if (RPC_S_OK != eStatus)
{
goto lblCleanup;
}
// Encode the struct.
RpcTryExcept
{
MY_STRUCT_Encode(hEncoder, &tStruct);
}
RpcExcept(RpcExceptionFilter(RpcExceptionCode()))
{
eStatus = RpcExceptionCode();
goto lblCleanup;
}
RpcEndExcept
// Create a decoding handle from the buffer we got.
eStatus = MesDecodeBufferHandleCreate(pcEncoded, cbEncoded, &hDecoder);
if (RPC_S_OK != eStatus)
{
goto lblCleanup;
}
// Decode the struct from the buffer.
RpcTryExcept
{
MY_STRUCT_Decode(hDecoder, &tDecoded);
}
RpcExcept(RpcExceptionFilter(RpcExceptionCode()))
{
eStatus = RpcExceptionCode();
goto lblCleanup;
}
RpcEndExcept
// Verify that the decoding succeeded.
assert(tStruct.dwSomeDword == tDecoded.dwSomeDword);
eStatus = RPC_S_OK;
lblCleanup:
if (NULL != hDecoder)
{
(VOID)MesHandleFree(hDecoder);
hDecoder = NULL;
}
if (NULL != pcEncoded)
{
midl_user_free(pcEncoded);
pcEncoded = NULL;
}
if (NULL != hEncoder)
{
(VOID)MesHandleFree(hEncoder);
hEncoder = NULL;
}
return (INT)eStatus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment