Search code examples
c#c++appdomainmarshalbyrefobjectnetmodules

Unable to create object in another appdomain when invoking C# using C++


I have created a C# code with output type as netmodule. This is being used in a C++ code.

I want to create an object of the same assembly which is already loaded. But, in a separate AppDomain. But when doing this, I am unable to load the assembly to create the object using CreateInstanceAndUnwrap method. When trying to do the same using a standalone C# code, it works fine.

C++:

TestClass __gc *testObj;
testObj = AppDomainProcessor::getInstance()->newTestObj((LPWSTR)domName);
//testObj->otherOperation...

C#

namespace TestNS {
public class AppDomainProcessor {
...
public TestClass newTestObj(String domName) {
AppDomain appDomain = AppDomain.CreateDommain(domName);


  TestClass testObj = (TestClass)appDomain.CreateInstanceAndUnwrap(typeof(TestClass).Assembly.FullName,typeof(TestClass).FullName);
//Could not load file or assembly 'MyManaged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified
    return testObj;
    }
...
}

public class TestClass : MarshalByRefObject {
...
}
}

I printed the AssemblyName and found it as the name of the dll which is compiled from the C++ code. When trying from standalone C#, it was the name of the exe.

Is this a proper way of creating AppDomain when using C++ and C# together? Or I have made any mistake in creating the AppDomain. Please assist.


Solution

  • Finally got it working. May be it didn't work as I am using a C++ Managed DLL.

    But even when I manually entered the DLL location and loaded using CreateInstanceFromAndUnwrap, It didn't work either. But when a Assembly resolving fails, it triggers the AssemblyResolve event. I am using the same Assembly which is executing to create the new AppDomain. Here is the code.

    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    
    Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
                return Assembly.GetExecutingAssembly();
            }
    

    When unable to load, it returns the current Assembly and works fine.