Unable to cast transparent proxy (AppDomain.CreateInstanceFromAndUnwrap) RRS feed

  • Question

  • I'm writing a .NET library to inject managed DLLs into external processes. My current approach is:

    1. Use CreateRemoteThread to force the target process to call LoadLibrary on an unmanaged bootstrap DLL. From this point we're executing code in the target process.
    2. My bootstrap DLL then creates an instance of the CLR and calls ExecuteInDefaultAppDomain on it, which executes a method in a managed helper DLL.
    3. This method creates a new AppDomain and calls AppDomain.CreateInstanceFromAndUnwrap to pass execution into my payload DLL, casting the result as an IInjectionPayload .
    4. The idea is that my payload DLL exposes a class which implements IInjectionPayload , so the helper DLL can simply call payload.Run() .

    I'm doing it this way so that the payload code can be completely unloaded by simply calling AppDomain.Unload (after signalling it to clean up).

    This approach works - the class in my payload DLL is getting instantiated in the target process, so code can be executed - but I can't cast the object returned by CreateInstanceFromAndUnwrap to an IInjectionPayload ; it throws the following exception:

    Unable to cast transparent proxy to type 'blah.Blah.IInjectionPayload'.

    I've tried using CreateInstanceAndUnwrap , and Activator.CreateInstanceFrom followed by Object.Unwrap , but both of these methods also cause the same exception to be thrown.

    The signature of my payload class is:

    public class Program : MarshalByRefObject, IInjectionPayload

    I'm stumped because the payload DLL is definitely getting loaded and the class is being instantiated, as intended. Any help would be much appreciated.

    Thursday, September 17, 2009 10:24 AM


  • The usual hangup with this is that you've got two distinct types that are named IInjectionPayload.  One that's stored in your injector, another that's stored in the payload, produced by the same source code file being compiled into both assemblies.  They are distinct types because they come from two different assemblies.  You need a 3rd assembly that declares IInjectionPayload, referenced by the two other ones.

    Hans Passant.
    • Marked as answer by eryang Wednesday, September 23, 2009 2:07 AM
    Thursday, September 17, 2009 6:53 PM