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

时间:2021-10-03 12:59:28

I have a test that I'm writing in MSTest, which is managed C++, and I'm trying to test an unmanaged class. Specifically, I'm trying to use the PrivateObject class to call a private method.

我有一个测试,我在MSTest中编写,它是托管C ++,我正在尝试测试一个非托管类。具体来说,我正在尝试使用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^. I've tried doing the following:

当我编译时,我得到一个错误,foo不能转换为System :: Type ^。我尝试过以下操作:

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

but that won't work because System::Type^ is an abstract type. Any ideas?

但这不起作用,因为System :: Type ^是一种抽象类型。有任何想法吗?

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? Conversion between managed and unmanaged types in C++?

我看过这些问题,但是他们使用了预定义的类型,而不是用户定义的类型:如何将非托管双精度转换为托管字符串?在C ++中托管和非托管类型之间的转换?

1 个解决方案

#1


The PrivateObject constructor wants a typename, not an instance. To do this, you would need to do the following:

PrivateObject构造函数需要typename,而不是实例。为此,您需要执行以下操作:

PrivateObject privateFoo = gcnew PrivateObject( "CUnmanagedType" )

#1


The PrivateObject constructor wants a typename, not an instance. To do this, you would need to do the following:

PrivateObject构造函数需要typename,而不是实例。为此,您需要执行以下操作:

PrivateObject privateFoo = gcnew PrivateObject( "CUnmanagedType" )