简体   繁体   English

如何将用户定义的非托管类型转换为托管类型?

[英]How to convert a user-defined unmanaged type to a managed type?

I have a test that I'm writing in MSTest, which is managed C++, and I'm trying to test an unmanaged class. 我有一个用MSTest(托管C ++)编写的测试,并且正在尝试测试非托管类。 Specifically, I'm trying to use the PrivateObject class to call a private method. 具体来说,我正在尝试使用PrivateObject类来调用私有方法。

This is the code that I have so far: 这是我到目前为止的代码:

CUnmanagedType foo;
PrivateObject privateFoo = gcnew PrivateObject( foo );

CString strFromFoo = privateFoo.Invoke( "ARandomPrivateMethod" );

When I compile I get an error that foo is not convertable to System::Type^. 当我编译时,我得到一个错误,即foo无法转换为System :: Type ^。 I've tried doing the following: 我尝试执行以下操作:

PrivateObject privateFoo = gcnew PrivateObject( (gcnew System::Type^(foo)) );

but that won't work because System::Type^ is an abstract type. 但这不起作用,因为System :: Type ^是抽象类型。 Any ideas? 有任何想法吗?

I've looked at these questions, but they used pre-defined types, not user-defined ones: How to convert a unmanaged double to a managed string? 我看过这些问题,但它们使用的是预定义类型,而不是用户定义的类型: 如何将非托管double转换为托管字符串? Conversion between managed and unmanaged types in C++? 在C ++中托管类型和非托管类型之间的转换?

The PrivateObject constructor wants a typename, not an instance. PrivateObject构造函数需要一个类型名,而不是一个实例。 To do this, you would need to do the following: 为此,您需要执行以下操作:

PrivateObject privateFoo = gcnew PrivateObject( "CUnmanagedType" )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM