Un argument d'attribut doit être une expression constante est-il un moyen de contourner cela en C #?

StackOverflow https://stackoverflow.com/questions/2321103

  •  22-09-2019
  •  | 
  •  

Question

Je travaille sur un code (WinForms C # .NET 3.5) qui consiste à utiliser unrar.

    [DllImport("UNRAR64.DLL")]
    private static extern IntPtr RAROpenArchive(ref RAROpenArchiveData archiveData);
    [DllImport("UNRAR64.DLL")]
    private static extern IntPtr RAROpenArchiveEx(ref RAROpenArchiveDataEx archiveData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARCloseArchive(IntPtr hArcData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARReadHeader(IntPtr hArcData, ref RARHeaderData headerData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARReadHeaderEx(IntPtr hArcData, ref RARHeaderDataEx headerData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARProcessFile(IntPtr hArcData, int operation, [MarshalAs(UnmanagedType.LPStr)] string destPath, [MarshalAs(UnmanagedType.LPStr)] string destName);
    [DllImport("UNRAR64.DLL")]
    private static extern void RARSetCallback(IntPtr hArcData, UNRARCallback callback, int userData);
    [DllImport("UNRAR64.DLL")]
    private static extern void RARSetPassword(IntPtr hArcData, [MarshalAs(UnmanagedType.LPStr)] string password);

Comme je veux le code à travailler sur les deux 32bits et 64bits je voulais assigner UNRAR64.DLL ou unrar.dll via une chaîne unrarDll en fonction de contrôle pour bitness du système.

    private void DllChoice() {
        if (SystemIs64Bit()) {
            sevenZipDll = "7z-x64.dll";
            unrarDll = "unrar.dll";
        } else {
            sevenZipDll = "7x-x32.dll";
            unrarDll = "unrar64.dll";
        }
    } 
    private static bool SystemIs64Bit() {
        return (IntPtr.Size == 8);
    }

erreur est renvoyée:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Y at-il moyen facile de contourner cela? Quelle serait la bonne façon de le faire?

Était-ce utile?

La solution

pas :-) il fait partie de la spécification ... vous devez avoir deux builds pour chaque plate-forme (x86 / x64). Ce que vous pouvez faire est de définir simplement une directive préprocesseur, et faire quelque chose comme

#if x64
// ... define all x64 imports here
#else
// ... define all x86 imports here
#endif

Autres conseils

Créer une interface pour les importations unrar et mettre en œuvre 32 bits et 64 bits versions séparément. Si 32 bits, instancier 32 impl bits, sinon instancier les 64 impl bits.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top