Force x86 CLR on an 'Any CPU' .NET assembly
Solution 1:
You can find out how an application will run and change it statically using the CorFlags application. To find out how the application will run, use:
corflags <PathToExe>
To change how the application will run, use:
corflags /32bit+ <PathToExe>
This will make the EXE file run as a 32-bit process. The information about how the assembly should run is stored in the PE header. See Stack Overflow question How to find if a native DLL file is compiled as x64 or x86?.
If you want to inject code at run time, you have to write a .NET profiler in C++/COM. See .NET Internals: The Profiling API and Profiling (Unmanaged API Reference) for more details.
You'll need to implement the JitCompilationStarted callback and do your work there. If you go in this direction, you'll have to build the injecting DLL file both as x86 and x64. The native DLL files will be loaded by the CLR once the following environment variables will be set:
Cor_Enable_Profiling=0x1
COR_PROFILER={CLSID-of-your-native-DLL-file}
If you have it set correctly then the 64-bit version will 'see' the 64 bit processes and the 32-bit version will 'see' the 32-bit processes.
Solution 2:
It has been a while since I tried this, but I believe that the bitness of the process that calls the assembly determines whether it will be JITed as x86 or x64.
So if you write a small console application and build it as x86, and another as x64, running one or the other will cause other assemblies loaded into the process to run as 32 or 64 bit. This, of course, assumes you are running on a 64 bit machine.