使用 C++ 调用 C# 时无法在另一个应用程序域中创建对象

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

我创建了一个输出类型为 netmodule 的 C# 代码。这正在 C++ 代码中使用。

我想创建一个已加载的同一程序集的对象。但是,在一个单独的 AppDomain 中。但是这样做时,我无法加载程序集以使用 CreateInstanceAndUnwrap 方法创建对象。当尝试使用独立的 C# 代码执行相同操作时,它工作正常。

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 {
...
}
}

我打印了 AssemblyName 并发现它是从 C++ 代码编译的 dll 的名称。从独立 C# 尝试时,它是 exe 的名称。

同时使用 C++ 和 C# 时,这是创建 AppDomain 的正确方法吗?或者我在创建 AppDomain 时犯了任何错误。请协助。

终于成功了。可能是它不起作用,因为我使用的是 C++ 托管 DLL。

但即使我手动输入DLL位置并使用CreateInstanceFromAndUnwrap加载,它也不起作用。但是当 Assembly 解析失败时,它会触发 AssemblyResolve 事件。我正在使用正在执行的同一个程序集来创建新的 AppDomain。这是代码。

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
            return Assembly.GetExecutingAssembly();
        }

当无法加载时,它returns当前程序集并且工作正常。