Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# visual studio build exe with target anycpu but that determines its platform(x86/x64) on the calling process platform(x86/x64)

We have a software in 32 and 64 bits that calls our exe and passes events to it(like a plugin).

The thing is that our exe has to execute in the same bitness(x86/x64) as the calling software (if the software is run in 32 bits version our exe must run in 32 bits, if the software is run in 64bits version our exe must run in 64 bits). The windows version is 64bits but the client can run the software in 32bits version or 64bits version.

In visual studio(2015) the Target AnyCPU option only depends of the windows version(+ Prefer 32-bit checkbox) but we need to be dependent on the calling software Process.

Is there any option or solution we can implement instead of compiling to each platform (x86 and x64)?

like image 800
VSP Avatar asked Jan 26 '17 11:01

VSP


1 Answers

There is no Windows operating system requirement that two separate processes need to be the same bitness to communicate with each other-- so I'm assuming you have some internal requirement that both processes be the same bitness. If you absolutely must achieve dynamically running the same EXE in either 32-bit or 64-bit and make that decision at runtime, you can modify your AnyCPU compiled app at run time using corflags.exe utility that ships with Visual Studio.

You can launch corflags.exe like this (using System.Diagnostic.Process):

corflags.exe "ourapp.exe" /32BIT+

To force it to run 32bit, and

corflags.exe "ourapp.exe" /32BIT-

To go back to AnyCPU (which will be 64-bit on a 64-bit OS)

The solution would be that you would deploy a copy of corflags.exe in your runtime environment. Then, your host application can detect it's current bitness by checking sizeof(IntPtr) to see if it is 8 or 4; and spawn a copy of corflags.exe accordingly (using System.Diagnostics.Process), prior to launching the ourapp.exe.

This is very HACKY. Be careful. Obviously you will have lots of trouble if you need to run two copies of your ourapp.exe at the same time on the same machine. It would be ideal to create a unique copy of ourapp.exe to a local user folder before modifying it and launch it from there to avoid race conditions from multiple instances and UAC prompts depending on your target environment.

like image 93
Tim Avatar answered Oct 22 '22 17:10

Tim