Q I'm in the process of converting an existing C ++ class library to the managed extensions so I can expose it to my. net Framework-based clients. some of my code cils api functions that require the hinstance of the current running module. I don't want to use the hinstance of my DLL; I want the caller to supply the hinstance of the EXE calling my DLL. I can declare the hinstance parameter as an int PTR, But how do my. Net-based clients get the app's hinstance to pass to my function? For example, how wocould they do it in C #?
Hunter Gerson
A good question! This one stumped me for about 15 minutes. in MFC you can call AfxGetInstanceHandle (). MFC stores the hinstance in its application object, in cwinapp: m_hinstance. so if you're using the Microsoft. NET Framework, you might think that you shoshould take a look in the Application Object for application. hinstance or an application property or some such thing. Why not? Because it's not there!
If you search the framework documentation for "hinstance," you'll discover there's a method named Al. gethinstance. well, that sounds promising. this static marshal method requires the module whose hinstance you want to obtain:
// In C#
Module m;
...
IntPtr h = Marshal.GetHINSTANCE(m);
Now you know how to get the hinstance-but where do you get the module? Again, you might think to look in the application class for something like application. getmodule. or perhaps application is derived from module, that wocould make sense. alas, neither is true. well, maybe there's a module property. nope. well, not quite. there is a module property, but it's not a property of the application, it's a type property. in. net Framework, every object has a type and every type has a module. type. module represents whichever module implements the type. so to get the hinstance of the calling module, your clients can write:
Type t = myObj.GetType();
Module m = t.Module;
IntPtr h = Marshal.GetHINSTANCE(m);
You can also use typeof (-- typeof in C ++) to get the type without an object instance, as in typeof (MyApp ). just tell your MERs to make sure they use a type that's implemented in the calling module. if you use some other type-for example, one of the Framework types like string-you'll get the wrong module.
Figure 1 shows a simple C # console app, showmodule, that has strates this. figure 2 shows it running. showmodule displays module information including the hinstance for two types: The MyApp class defined in the application itself and the string [] (String Array) type defined in mscorlib.
Figure 2 module information