Runtime platform dependent DllImportAttribute would be awsome RRS feed

  • Question

  • Hello, I think I have not an easy question today. I really need some functionality which is written in C++ and there is no a C# port. I can download the source code and compile it as x86 and x64 DLL. I can also use DllImport and call the library, this works great (.NET did not have codename "COM 2.0" for no reason). I can also detect a platform on runtime and rename appropriate library. Why on runtime instead of compile time directive? I call a native library from the other library which can live in Azure Virtual machine or in Azure Cloud service in Web role or Worker role and I want to keep .NET platform independence.

    static MyClassStaticConstructor() {
        try {
            var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var lib = Path.Combine(dir, "myNativeLib.dll");
            var libx86 = Path.Combine(dir, "myNativeLib.x86.dll");
            var libx64 = Path.Combine(dir, "myNativeLib.x64.dll");
            if (!File.Exists(lib)) {
                var permission = new FileIOPermission(FileIOPermissionAccess.Write, dir);
                permission.Demand(); // exception - Access to the path is denied.
                if (Environment.Is64BitProcess) {
                    File.Move(libx64, lib);
                } else {
                    File.Move(libx86, lib);
        } catch (Exception ex) {
            // error handling

    The problem is that this is not working inside Azure Cloud service. It works in the Windows Azure Compute Emulator however.

    What is a recommended pattern to reference a native library depending on platform?

    Create a symbolic link? It is file system dependent.

    Use overloaded methods for x84 and x64 variant each with a different path in the DllImportAttribute? It is too complicated.

    Rename appropriate DLL file platform version? Write permission required.

    My feature request for .NET 5:

    [DllImport("myNativeLib.x64.dll", UseIn64BitProcess = true)]
    void MyNativeMethod() { }
    Tuesday, June 4, 2013 10:40 AM


  • I dont think its an supported operation in cloud services, you would need Virtual machine as your roles to perform these operations

    ---------------------------------- Please mark as answered if it helped Vishal Narayan Saxena

    Tuesday, June 4, 2013 5:21 PM