Tuesday, October 05, 2004

Calling Windows APIs from managed code – Good/Bad?

Windows application programming interfaces (API) are dynamic link libraries (DLLs) that are part of the Windows operating system. The .NET framework has wrapped major segment of the Win32 API into managed code. But still there are few remaining portion of unmanaged part that you can make use of that functionality using the platform invoke service.

You have to be aware the following things about calling Windows APIs from managed code:

1. Windows APIs are part of unmanaged world.

2. Windows APIs doesn’t have built-in type libraries and the data types used in managed code is entirely different.

3. Windows API’s are not COM Objects.

4. To make use of the Windows API functionalities, you have to make use of Platform invoke (PInvoke), which enables managed code to call the unmanaged functionality provided by Windows DLL’s.

5. The Platform Invoke service offers a method to call functions that are exported from an unmanaged DLL. The most distinctive use of PInvoke is to allow .NET components to interact with the Win32 API. PInvoke is also used to access functions exports defined in custom DLLs.

6. In behind the scenes the Platform Invoke will locate the DLL contain the function, load the DLL into memory and locating the address of the function in memory and invokes an exported function and marshals its arguments.

For more info check here: Consuming Unmanaged DLL Functions

Check my article on COM Interop:
http://www.microsoft.com/india/msdn/articles/24.aspx

Advantage:

1. Development time is less. Just utilize the function and get the functionality you required from the already written useful functions.

2. Less Complex (if you know the definition and usage of PInvoke signatures!). Make use of these functions, which are tricky to do in managed code.

Disadvantage:

1. If you don’t know the exact PInvoke signature, you are in trouble; it will take lot of time! I suggest visiting http://www.pinvoke.net before you try anything.

2. Win API’s are merciless when things go wrong. If you make any error, you’ll possibly corrupt memory.

3. More PInvoke calls - Performance is an issue, due to the data marshaling.

No comments: