Wednesday, 29 April 2009

Assembly.Load C++ CLI assembly gives Unverifiable code failed policy check

This is one of those problems that I couldn’t find the answer with google.

Trying to load a C++ mixed mode assembly (like a CLR class library) from a byte array instead of a file throws a FileLoadException.

            // ClassLib.dll is a mixed-mode assembly (from a C++ CLR Class Library project

 

            Assembly.Load("ClassLib"); // Works

 

            using (var stream = new FileStream("ClassLib.dll", FileMode.Open, FileAccess.Read))

            {

                var bytes = new byte[stream.Length];

                stream.Read(bytes, 0, bytes.Length);

 

                Assembly.Load(bytes); // System.IO.FileLoadException "Unverifiable code failed policy check. (Exception from HRESULT: 0x80131402)"

            }

5 comments:

  1. Hi,
    Did you find an answer to this ? This is annoying, and I have come across it too. Basically it seems you have to stream the files from your binary stream to disk, then use Assembly.Load. I am remoting and wanted to stream DLLs, not have to write them to disk, but cannot if they have native code inside.

    Sean.

    ReplyDelete
  2. Since I couldn't build the C++ assembly with /clr:safe (apparently that will fix the problem) I had to load it from disk like you're doing.

    ReplyDelete
  3. Same probleme here :(

    ReplyDelete
  4. Yes, you can't do that, and here's why: http://connect.microsoft.com/VisualStudio/feedback/details/97801/loading-mixed-assembly-with-assembly-load-byte-throw-exception-changed-behaviour

    ReplyDelete
  5. I guess the mechanisms that windows uses to load a native/mixed-mode dll from disk can't be applied to an arbitrary set of pages in memory - probably because there's no API equivalent to LoadLibrary to do it.

    ReplyDelete