Loading assemblies from memory when placing the CLR in unmanaged programs
I was able to host the CLR in an unmanaged program thanks to the rich documentation. However, when hosting the CLR, it looks like it is limited to loading assemblies from the hard drive - when you run a managed application, you can load assemblies from memory by calling Assembly.Load () though.
Is there a way to do a hosted CLR build from memory? How:
- Writing a managed assembly to memory
- Initiate CLR
- Launch CLR
- Perform guided memory build
- Wait for the managed assembly to return.
- Stop CLR
I've searched the internet and MSDN for hours but couldn't find a solution to this problem! The workaround I came up with would involve another assembly that calls Assembly.Load (). However, I am afraid this might be overkill.
Thanks in advance for tips or advice!
source to share
I suggest you start with this example here: C ++ app hosts CLR 4 and calls the .NET assembly (CppHostCLR) , which seems to do almost what you need. The only missing piece is not loading the assembly from memory, but using the file.
So, you just need to replace the following lines (in RuntimeHostV4.cpp):
// Load the .NET assembly.
wprintf(L"Load the assembly %s\n", pszAssemblyName);
hr = spDefaultAppDomain->Load_2(bstrAssemblyName, &spAssembly);
if (FAILED(hr))
{
wprintf(L"Failed to load the assembly w/hr 0x%08lx\n", hr);
goto Cleanup;
}
with the following lines that use this method instead: _ AppDomain.Load method (Byte [])
// let suppose I have a LPBYTE (pointer to byte array) and an ULONG (int32) value
// that describe the buffer that contains an assembly bytes.
LPBYTE buffer = <my buffer>;
ULONG size = <my buffer size>;
// let create an OLEAUT SAFEARRAY of BYTEs and copy the buffer into it
// TODO: add some error checking here (mostly for out of memory errors)
SAFEARRAYBOUND bounds = { size, 0 };
SAFEARRAY *psa = SafeArrayCreate(VT_UI1, 1, &bounds);
void* data;
SafeArrayAccessData(psa, &data);
CopyMemory(data, buffer, size);
SafeArrayUnaccessData(psa);
hr = spDefaultAppDomain->Load_3(psa, &spAssembly);
if (FAILED(hr))
{
wprintf(L"Failed to load the assembly w/hr 0x%08lx\n", hr);
goto Cleanup;
}
SafeArrayDestroy(psa); // don't forget to destroy
source to share