Activator::CreateInstance( unmanaged type )

M

muriwai

Hi,

VC++ 2008 /clr:

I have an unmanaged class: "class U" and managed one: "class ref M{ M(
const U* ); }". In other words, the constructor of the managed class M
takes the pointer to the unmanaged class U. I can call the constructor
directly no problem. I want to instantiate M via reflection.

Activator::CreateInstance() takes an array of parameters to be passed to the
constructor:

array< System::Object^ >^ pParams = gcnew array< System::Object^ >( 1 );
const U* pu = new U;
pParams[ 0 ] = pu;

The last line gives error C2440: '=' : cannot convert from 'const U *' to
'System::Object ^

My question is, how do I pass a pointer to an unmanaged class as a
constructor parameter to Activator::CreateInstance()?

Thank you,

Andrew
 
J

Jochen Kalmbach [MVP]

Hi muriwai!
array< System::Object^ >^ pParams = gcnew array< System::Object^ >( 1 );
const U* pu = new U;
pParams[ 0 ] = pu;

For "pointers" you should use "System::IntPtr"

Greetings
Jochen
 
M

muriwai

Thanks Jochen. I tried the following:

const U* pu = new U;
pParams[ 0 ] = gcnew System::IntPtr( ( PVOID) pu );
Activator.CreateInstance( type, pParams );

but the last line throws an exception because it can't find the constructor
(the constructor is "internal" by the way, and I am calling from the same
DLL).

I ended up with type->GetConstructors() and then explicitly invoking the
constructor with IntPtr as a parameter.

Cheers


Jochen Kalmbach said:
Hi muriwai!
array< System::Object^ >^ pParams = gcnew array< System::Object^ >( 1 );
const U* pu = new U;
pParams[ 0 ] = pu;

For "pointers" you should use "System::IntPtr"

Greetings
Jochen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top