C # projects using both X86 and Any CPU

Say I have 2 Winform A, B projects.

Project A (target .NET 2.0) must be running on x86 (this is an external library), and for old reasons, Project B (target .NET 4.0) must be running on any processor. Now I need to call the methods from project B, but it throws an error:

"An unhandled exception of type 'System.BadImageFormatException' occurred in System.Windows.Forms.dll" Additional information: Could not load file or assembly 'CSharpDemo, Version=1.0.5414.18636, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format." 

However, I found that if I target Project B on .NET 4.5, this problem does not occur. But I still want Project B to be guided by 4.0, how to achieve this?

+5
source share
2 answers

If any of your codes calls 32-bit x86 libraries, the whole process needs to be downloaded as x86. There are no exceptions.

To do this, install the EXE project on x86, install DLL projects with native x86 dependencies on x86, and for clean managed DLL projects you can use AnyCPU -.NET will load them as x86 for your x86 EXE, but they can also load to x64 exe.

Remember that x86 code works great on x64 processors running x64 Windows using the WOW64 compatibility level.

(with a few exceptions: at the release of Windows Server, WOW64 is an optional component, and there is no WOW64 in the preinstallation environment).

+8
source

You can find the answer to your question in the next blog post

http://blogs.microsoft.co.il/sasha/2012/04/04/what-anycpu-really-means-as-of-net-45-and-visual-studio-11/

Here is a summary

.net 4.0

What AnyCPU means for .NET 4.0 (and Visual Studio 2010) is the following:

โ€ข If the process runs on a 32-bit Windows system, it runs as a 32-bit process. IL compiles to x86 machine code.

โ€ข If the process runs on a 64-bit Windows system, it runs as a 64-bit process. IL compiles to x64 machine code.

โ€ข If the process runs on an Itanium Windows system (does anyone have one? ;-)), it works as a 64-bit process. IL compiled for Itanium machine code.

.net 4.5

In .NET 4.5 and Visual Studio 11, cheese has been moved. The default for most .NET projects is again AnyCPU, but there is more than one value for AnyCPU now. There is an additional subtype of AnyCPU, "Any CPU is 32-bit preferred", which is the new default value (in general, there are now five options for C # / compiler: x86, Itanium, x64, anycpu and anycpu32bitpreferred). When using this flavor of AnyCPU, the semantics are as follows:

โ€ข If the process runs on a 32-bit Windows system, it runs as a 32-bit process. IL is compiled for x86 machine code.

โ€ข If the process runs on a 64-bit Windows system, it runs as a 32-bit process. IL compiles to x86 machine code.

โ€ข If the process runs on an ARM Windows system, it runs as a 32-bit process. IL compiles to ARM machine code.

+4
source

Source: https://habr.com/ru/post/1205648/


All Articles