4

Is it a valid scenario to reference an x64-dll from an AnyCpu dll when the system it will run on is for sure a 64bit System?

I'm asking, because I had issues here, getting an exception as follows:

"Could not load file or assembly 'XY' or one of its dependencies.An attempt was made to load a program with an incorrect format"

I had this problem several times with different solutions in the last couple of years. Sometimes it seems to work and sometimes not.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
DanielG
  • 1,217
  • 1
  • 16
  • 37
  • If it will be able to run only on 64 bit system, then you should target x64 – Matteo Umili Jul 08 '15 at 10:07
  • 1
    Yes that's valid. It goes wrong so often because programmers tend to not know how to configure their solution correctly to ensure it will actually run in 64-bit mode. They'll change the solution platform name, not relevant to managed projects, or forget to change the setting for the Release configuration. Only the "Target platform" setting on the EXE project matters. – Hans Passant Jul 08 '15 at 10:11
  • yeah, you're right. But the question was more in general. just want to know if it is valid to reference x64 from anycpu. – DanielG Jul 08 '15 at 10:12
  • It isn't a good practice because it will work only if you run the AnyCPU assembly on a x64 system, so targeting AnyCPU will be meaningless – Matteo Umili Jul 08 '15 at 10:19
  • I agree that it is meaningless...but I'm still not sure that it is valid. I had several issues where it did not work as expected. So I thought that it might not be a valid scenario and we will get unexpected behavior, so that it might work but it is not guaranteed. – DanielG Jul 08 '15 at 10:21

1 Answers1

2

It is completely valid for an AnyCPU assembly to target an x64 DLL. But, it is up to you to ensure that your AnyCPU assembly is actually executing as an x64 process.

Note that later versions of Visual Studio have added the "Prefer 32-bit" option to assemblies. So you need to make sure this is turned off, and that you aren't using any settings on the machine that would override that setting.

Also note that if your AnyCPU assembly references other assemblies that may be available only as x86 assemblies on the target machine, it will be run as an x86 process.

Frankly, if you know that you want the process to only ever run as x64, IMHO it makes the most sense to compile it as x64. At least that way, if you do wind up running it in an incompatible environment, you'll get a better error message (i.e. the event log will contain the information about the dependency that was incompatible with your process, instead of some other dependency that is actually as expected).

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136