CLR Hosting - .Net 4.0, .Net 2.0, take your pick


I've recently been adjusting my CLR hosting code as a client wanted to be able to host the .Net 4.0 runtime. Previously they were hosting the 2.0 runtime and, as I mentioned a while back, the hosting API has changed with 4.0.

Switching to hosting 4.0 was easy enough but being able to fall back to hosting 2.0 on a machine where 4.0 wasn't installed is slightly more complex. It's reasonably obvious (you need to make sure that you call GetProcAddress() to bind to CLRCreateInstance() rather than linking to it at build time), but Brad Wilson has a nice list of steps to show how it's done here on his blog.

There still seems to be some complexity with regards to selecting the most appropriate version of the CLR for a given assembly as whilst ICLRMetaHost::GetVersionFromFile() will, for example, give you "v1.0.3705" for a CLR 1.0 assembly and "v1.1.4322" for a CLR 1.1 assembly which is fine but ICLRMetaHost::GetRuntime() wont apply any machine policies to give you a v2.0 or whatever CLR if you ask it for v1.0.3705 and it's not installed.

I'm probably missing something in the API somewhere and it's not really that much of a problem for me right now, I already have a version munging stage which allows things like "v2.0" to mean 'the latest greatest v2.0 you have please (purely for when the next version comes out and the build is changing with the betas...) and which can be told to default to the latest CLR available if the specified one isn't found, or to fail the request, etc.

Leave a comment