четверг, 11 сентября 2014 г.

Preparing to MS Exam 70-483 - Ensure Interoperability With Unmanaged Code

The full set of questions I'm trying to cover in time of my preparation to MS Exam 70-483 you can find here.



Interoperability enables managed code to work with unmanaged one (code which is not under control of CLR) that is why we can use, for example, Win32 API and ActiveX.

There are two techniques which enables using unmanaged code from managed one:
  • Platform Invoke (shortly P/Invoke)
  • COM Interop



Platform Invoke


To use unmanaged methods, provided by Win32 API, we shoul declare them with [DllImportAttribute] which is part of System.Runtime.InteropServices.
[DllImport("name.dll", CharSet = CharSet.Auto, EntryPoint = "MessageBox", SetLastError = true/false)] 
NOTES
  • By default EntryPoint is the name of the method 
  • If there is an error, the program can use GetLastWin32Error to see what went wrong.
The attribute should be applied to a static extern method declaration.


For instance, to call Win32 Message/Dialog Box we should declare:
        [DllImport("user32.dll")]
        public static extern int MessageBoxA(int h, string text, string caption, int options); 
As soon as we'll do this we will be able to call Win32 method  MessageBoxA:
Method will return value according pressed button:
OK
1
Cancel
2
Abort
3
Retry
4
Skip
5
Yes
6
No
7

Sometimes you need more control over conversion between managed and unmanaged code, and this control provides [MarshalAsAttribute] which you can add to the method’s parameters or return value. The following code shows a new version of the DllImport:
The first MarshalAs attribute indicates that the first parameter is an I4 data type in the unmanaged code and should be treated as a int in the managed code, the second MarshalAs attribute indicates that the second parameter is an LPStr data type in the unmanaged code and should be treated as a stringin the managed code and so on

NOTE
[UnmanagedFunctionPointerAttribute] controls the marshaling behavior of a delegate signature passed as an unmanaged function pointer to or from unmanaged code. 


COM Interop 

To use COM Interop you need to give a reference to appropriate library, this will give Visual Studio some information about unmanaged resources. Despite of this information VS may still not understand some COM types and this will cause design-time errors,
Dynamic keyword is the solution in the situation, it makes variables to be evaluated at Run-time.  
Here is the example of implicit using of dynamic keyword: