lundi 10 juillet 2023

Hosting CLR: Calling .NET constructors/methods reflectively from C when some parameters are Enums

I have a native program that hosts the CLR (i.e. starts it up manually, gets a reference to an AppDomain, etc. - this is not C++/CLI). Within that context, I want to instantiate a FileStream object.

To my understanding, the best way of creating objects in this context is to use reflection:

SAFEARRAY* pArgs = SafeArrayCreateVector(VT_VARIANT, 0, 2);
...
BSTR assemblyName = SysAllocString(L"mscorlib");
BSTR typeName = SysAllocString(L"System.IO.FileStream");
pAppDomain->CreateInstance_3(assemblyName, typeName, VARIANT_TRUE, BindingFlags_Default, NULL, pArgs, NULL, NULL, NULL, &result);

This works fine for all sorts of other types I've tried to create; e.g. MemoryStream. But FileStream specifically has got me stumped, seemingly because FileStream expects Enum types in its constructor (e.g. System.IO.FileAccess). If I try to give it a VT_I4 (the base type of the Enum) in the place of the FileAccess parameter, it complains that it can't find the constructor (HRESULT is COR_E_MISSINGMETHOD) - which does make sense... but given Enums are value types, there's no obvious VARIANT type to use.

Is there a way to use reflection in the context of using a hosted CLR, to invoke arbitrary constructors/methods, when some of the parameters are Enums?





Aucun commentaire:

Enregistrer un commentaire