- Platform Invoke (or P/Invoke) is sometimes required when we need to call Windows API or other unmanaged code which does not support .NET directly.
- System.Runtime.InteropServices namespaces is required. System.Runtime.CompilerServices may also be required.
- StringBuilder is preferrable over string during a P/Invoke.
- All that needs to be done is to create a static external method with same name as the name of the function that needs to be called and decorate it with DllImport attribute, specifying the unmanaged dll. (This would only be a function declaration, similar to like we'd be writing prototype for that function)
- After that whenever we call the function from within our managed code methods, the platform is invoked.
- If we wish to convert data type from unmanaged to managed code we may us MarshalAs Attribute over a field or a parameter and specify any of the UnmanagedType enum values.
- If an unmanaged function requires a callback, we may create a delegate specifying the signature that the callback method should possess, and while creating prototype for unmanaged code (one that requires a callback), give it an instance of that delegate. (See code on page 818)
- This means that we cannot send a method name directly in the callback parameter of an unmanaged function due to Type-Safety.
Friday, August 7, 2009
Chapter 13-Lesson 3
Labels:
callback,
delegate,
InterOp,
PInvoke,
Platform Invoke,
type safety,
Unmanaged Code,
Windows API
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment