我们有一个混合模式程序集,其中包含 VC++(使用 MFC)和 C++/CLI 类。它是一个 MFC 扩展 dll,在运行时加载到我们的 MFC 可执行文件中,一切正常。
当我们从另一个 C++/CLI 程序集中对其中的非托管类进行单元测试时,每次尝试(通过新)创建非托管类的实例时,都会看到以下异常:
Exception
System.TypeInitializationException: The type initializer for '<Module>' threw an exception. ---> <CrtImplementationDetails>.ModuleLoadExceptionHandlerException: A nested exception occurred after the primary exception that caused the C++ module to fail to load.
---> System.Runtime.Serialization.SerializationException: Serialization error.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie)
at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr , Void* )
at <CrtImplementationDetails>.LanguageSupport.InitializeDefaultAppDomain(LanguageSupport* ) in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 518
at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* ) in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 721
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 875
--- End of inner exception stack trace ---
at <CrtImplementationDetails>.ThrowNestedModuleLoadException(Exception innerException, Exception nestedException)
at <CrtImplementationDetails>.ThrowNestedModuleLoadException(Exception , Exception )
at <CrtImplementationDetails>.LanguageSupport.Cleanup(LanguageSupport* , Exception innerException) in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 841
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 883
at .cctor() in f:\dd\vctools\crt_bld\self_x86\crt\src\mstartup.cpp:line 922
--- End of inner exception stack trace ---
at MSMContactDataTests.LoadUnknownItemTest()
这看起来像是测试运行程序(在本例中为 Gallio.Echo)加载程序集失败。
我还创建了一个小型 C++/CLI 控制台应用程序并有效地尝试了同样的事情。我可以正确地创建包含在程序集中的 ref 类的实例,但是当我尝试新建一个未管理的类时,我得到了同样的异常。
有任何想法吗?
编辑
我打算发布在这里中断的控制台应用程序代码,但我已经重新编译它,它现在可以工作了!这里是:
#include "stdafx.h"
using namespace System;
#include "SCacheAssignment.h"
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
SCacheAssignment* assignment = new SCacheAssignment(NULL, false);
assignment->id = 2;
Console::WriteLine(L"Hello World 2 " + assignment->id);
return 0;
}
当我使用他的代码是一个单元测试:
#include "stdafx.h"
#include "PBSMSDataStoreUnitTests2.h"
#include "SCacheAssignment.h"
using namespace PBSMSDataStoreUnitTests2;
void Class1::SomeTest()
{
Console::WriteLine(L"Hello World");
SCacheAssignment* assignment = new SCacheAssignment(NULL, false);
assignment->id = 2;
Console::WriteLine(L"Hello World 2 " + assignment->id);
}
它打破了。这是测试程序集中的唯一测试。
控制台应用程序是一个 CLR 控制台应用程序,其中 CLR 类库中的测试程序集。据我所知,它们使用相同的编译器选项。为什么一种有效而另一种无效?