Search code examples
c#.net-3.5unrar

An attribute argument must be a constant expression is there a way around this in C#?


I'm working on a code (WinForms C# NET 3.5) that involves using 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);

Since i want the code to be working on both 32BIT and 64BIT i wanted to assign UNRAR64.DLL or UNRAR.DLL via a string unrarDll depending on check for bitness of system.

    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);
    }

Error is thrown:

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

IS there easy way around this? What would be the proper way of doing this?


Solution

  • no :-) it's a part of the spec ... you'll have to have two separate builds for each platform (x86/x64). What you can do is simply define a preprocessor directive, and then do something like

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