Ian Goldby
Ian Goldby

Reputation: 6174

Generate compiler error if platform target is not x86

How can I generate a compiler error if the platform target is not set to x86?

Motivation: A particular method dynamically loads a 32-bit COM dll. If the project is built for "x64" or "Any CPU" and is run in a 64-bit environment, then naturally loading the COM object fails at run time. I want a compile-time check to make sure this can't happen.

This is intended to be a safety check of the project settings, encapsulated entirely in the source file that requires 32-bitness. So I can't accept a solution (such as this) that requires defining a conditional compilation symbol in the project settings.

Upvotes: 1

Views: 271

Answers (2)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

You can write a Roslyn Diagnostic Analyzer to do this.

First, write something in your code to search for. You could use an attribute, for example. It could be an assembly level attribute, for example:

[assembly: Require32bit]

It could also be an attribute you apply to the class or even the method that is calling the COM component, as you choose.

Then write an analyzer to search for the presence of this. In the analyzer, you can use the Compilation.Options.Platform property to determine the platform. The compilation is available from e.g. the SyntaxNodeAnalysisContext.

Upvotes: 1

Gnqz
Gnqz

Reputation: 3382

Did you try something like:

#if PLATFORM_X86
    #error Target platform needs to be x86!
#endif

Upvotes: 0

Related Questions