Preprocessor directive in C# for importing based on platform

前端 未结 4 1929
别跟我提以往
别跟我提以往 2020-11-28 12:03

Looking for a preprocessor directive in c# for importing dll based on whether the executable is 64bit or 32 bit:

#if WIN64
[DllImport(\"ZLIB64.dll\", Calling         


        
相关标签:
4条回答
  • 2020-11-28 12:13

    Here's what you need to do.

    First, go into Project-><project name> Properties... and go to the Build tab.

    In there, in the textbox labelled "Conditional compilation symbols", add WIN32 for your x86 platform (selectable at the top of the dialog) and WIN64 for your x64 platform. Then save.

    Note that if you have one for "AnyCPU", you probably want to remove that platform altogether, as it won't be safe.

    Then, go into the source, and write this:

    #if WIN64
        [DllImport("ZLIB64.dll", CallingConvention=CallingConvention.Cdecl)]
    #else
        [DllImport("ZLIB32.dll", CallingConvention=CallingConvention.Cdecl)]
    #endif
    

    Note that when you view the source, one of the lines will look like it has been commented out, in that the entire line is in a gray font. This line is the one for the "other platform". If you select the platform in the toolbar, you'll notice that the syntax coloring follows suit.

    Of course, after re-reading my answer I notice that you don't actually need to put WIN32 into the conditional symbols list as it isn't used, but it might be useful other places to do an #if on WIN32 instead of 64.

    0 讨论(0)
  • 2020-11-28 12:13

    unload and edit the .csproj file, add:

      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
        <DefineConstants>WIN64;$(DefineConstants)</DefineConstants>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
        <DefineConstants>WIN64;$(DefineConstants)</DefineConstants>
      </PropertyGroup>
    

    use:

    #if WIN64
    ...
    #endif
    

    Regards

    0 讨论(0)
  • 2020-11-28 12:17

    You'll have to add a conditional compilation symbol for each target platform in your project's properties, in the Build tab. Simply add a symbol for the given Platform as determined by the Platform drop-down at the top of the Build form. Changing Platform will allow you do add different symbols that apply only to a build for that platform.

    0 讨论(0)
  • 2020-11-28 12:20

    There is nothing builtin that I am aware of. However, it is simple to define a custom compilation constant. If you are using Visual Studio create different build configurations for 32bit and 64bit versions using the Configuration Manager. Then open the project properties and go to the Build tab and enter a descriptive name in the conditional compilation symbols textbox for each build configuration. Then you can reference the compilation constants in code.

    0 讨论(0)
提交回复
热议问题