Why does this code throw System.AccessViolationException when called from a C# project targeting Any CPU?

时光毁灭记忆、已成空白 提交于 2019-12-02 08:11:49

What probably happens is you're (implicitely) using the same Type Library (.TLB), or DLL containing the .TLB, for the x64 and x86 versions.

The problem is your TLB defines an unmanaged structure, and this structure layout will be different in 32 bit and 64 bit mode (sizes, offsets, ...).

From .NET you want to make sure you're not referencing the same exact Interop Assembly (produced from the TLB by implicit tlbimp COM reference) when compiling with different processor architectures.

It can be tricky to get it right with standard Visual Studio tooling.

If you still want to use structs like this (which is kinda strange in the Automation world), I recommend you build Interop Assemblies using tlbimp.exe by yourself, and simply reference these Interop Assemblies like normal .NET assemblies, but depending on bitness (you will be able to tweak that using 'Condition' attributes in the .csproj) instead of using COM references directly.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!