• Like
CFInterop
Upcoming SlideShare
Loading in...5
×
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,268
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
19
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Compact Framework Interop Douglas Boling President Boling Consulting Inc. [email_address]
  • 2. About Me
    • Independent Windows CE consultant
      • Microsoft Embedded MVP
    • Writer
      • Author of “Programming Windows CE”
      • Various articles
    • Windows CE Instruction
        • Windows CE Application Development
        • Windows CE OAL and Drivers
        • .NET Compact Framework
    • www.bolingconsulting.com
  • 3. Agenda
    • Quick intro to the Compact Framework
    • What is Interop?
    • P/Invoke Basics
    • Marshalling
    • Calling native DLLs
    • Notifications from outside
    • What’s coming in Version 2.0
  • 4. Integration Imperative Web Applications Client Partner Partner Credit info Ad-hoc Screen scrape Email FAX B2C website HTML
  • 5. Integration Imperative Screen Scrape Client Website HTML
  • 6. Windows Embedded Platforms Windows XP Embedded The most complete embedded platform enabling advanced devices by delivering the power of Windows in componentized form Windows CE Windows CE integrates reliable real time capabilities with advanced Windows technologies to rapidly build a wide range of innovative, small-footprint devices
  • 7. .NET on Embedded Devices
    • Windows XP Embedded
      • Full v1.0 .NET runtime
        • 1.1 in SP2
      • Total compatibility
    • Windows CE .NET
      • Specially designed runtime
      • Smaller foot print
      • Tuned for low memory, low power devices
      • Limited to two languages
        • C#, Visual Basic .NET
  • 8.
    • In short: .NET runtime for small devices
      • CLR + subset of FCL
    • 1.0 supports
      • Pocket PC 2000, 2002
      • Windows Mobile 2003
        • Pocket PC and Smartphone
      • Windows CE .NET 4.1 and later
    • 2.0 supports
      • Windows Mobile 2003 for Pocket PC only
      • Windows CE 5.0 and later
    .NET Compact Framework
  • 9. Get the Latest Stuff!
    • Two service packs have been released
    • Service Pack 1
      • Bug fixes
    • Service Pack 2
      • Minor class library additions
      • Performance improvements
      • Bug fixes
    • Version 2.0 in Whidbey beta
  • 10. CF Similarities
    • Same type safe execution
      • No uninitialized variables
      • No unsafe casts
      • No bad array indexing
      • No bad pointer math
    • Similar garbage collection
      • No ref counting
      • No leaks
    • JIT compilation
      • Compiled code kept in memory
      • Pitched in low memory situations
  • 11. CF Similarities
    • Exceptions for error handling
    • Language neutral type system
      • Common scheme across all managed code
    • Use of assemblies
    • PE file format
    • Mutithread support
    • Windows Forms support
    • Can consume web services
  • 12. CF Difference Strategy
    • V1 support for client processing
      • Little support for devices as servers
    • Reduced resources on embedded devices
      • Less CPU power/system memory renders some .NET features impractical
    • CF Development schedule
      • They had to ship!
  • 13. CF Differences
    • No COM interop support
      • Use P/Invoke to call unmanaged functions
      • Manually create managed class that P/Invokes to DLL that then calls COM interfaces
    • No remoting
      • Client web services supported
    • No ASP .NET
    • No generic serialization
    • No install time compilation
      • No nGen
  • 14. CF Differences
    • No reflection emit
    • Domain neutral code areas not supported
    • Asynchronous delegates not supported
    • File change notifications not supported
    • No XML schema validation
    • No XML xpath queries
    • FCL Subset
  • 15. Other Changes
    • .NET CF Class library about 25% of desktop class library
    • Runtime tuned for embedded systems
      • Low memory devices
      • Low power CPUs
    • Extra classes added
      • IrDA classes
      • SQLCE classes
      • Pocket PC control support
      • MessageWindow class
  • 16. .NET CF Size
    • Approximately 1.3 Mbytes on Pocket PC (ARM)
    • Needs approximately 1 Meg of RAM
    • Application sizes quite small
      • 5 – 100k
  • 17. .NET Framework System.Web System.Windows.Forms System.Drawing System.XML System.Data System
    • Services
      • Description
      • Discovery
      • Protocols
    • UI
      • HTML Controls
      • Web Controls
    Security Session State Configuration Cache SQL Client SQL ServerCE Design ADO.NET IO Net Collections Security Reflection Resources Text Globalization Configuration Service Process Diagnostics Threading
    • Runtime
      • Interop Services
      • Remoting
      • Serialization
    Design Drawing 2D Imaging XML Document Xslt/XPath Serialization Reader/Writers Printing Text Component Model
  • 18. .NET Compact Framework System.Web System.Windows.Forms System.Drawing System.XML System.Data System
    • Services
      • Description
      • Discovery
      • Protocols
    • UI
      • HTML Controls
      • Web Controls
    Security Session State Configuration Cache SQL Client SQL ServerCE Design ADO.NET IO Net Collections Security Reflection Resources Text Globalization Configuration Service Process Diagnostics Threading
    • Runtime
      • Interop Services
      • Remoting
      • Serialization
    Design Drawing 2D Imaging XML Document Xslt/XPath Serialization Reader/Writers Printing Text Component Model
  • 19. .NET CF Interop
    • Why important?
      • The v1 release of .NET Compact Framework will not support everything necessary for a Windows CE application
      • Even if it did, embedded devices frequently need to be closer to the hardware than PC applications
  • 20. General Strategy
    • Enable developers to provide their own solutions
      • Decent P/Invoke support
      • COM ready managed threads
    • Basic support for notifying managed code of external events
      • Somewhat of an afterthought
  • 21. General Architecture
    • Managed applications are managed as Windows CE processes
      • Subject to the same limitations of a Windows CE process
        • 32/64 Meg memory space
        • DLL issues in Pocket PC 2002
      • Native DLLs are loaded into the process space of the managed application
    • Unmanaged DLLs not loaded until called
      • Call your unmanaged DLLs early
  • 22. What is Supported
    • Supported
      • Calling unmanaged functions in DLLs
        • “P/Invoke” support
    • Unsupported
      • Directly calling COM interfaces
        • Only by calling unmanaged DLLs that deal with COM objects
      • ActiveX controls
        • Third party solution available
  • 23. Steps for Calling Native Code
    • Decide what you need to do
    • Look for a managed way
      • Always choose the managed way before P/Invoke
    • Look in the SDK for the unmanaged call
      • Yes, you’ll still need to know the API
  • 24.
    • Create managed class to wrap P/Invoke calls
    • Declare an static, extern function with matching call parameters
    • Declare function as external
      • C# – Mark with the DllImport attribute
      • VB .NET – Use Lib keyword
    • Create public methods that call P/Invoke methods
    Steps for Calling Native Code
  • 25. Two General Possibilities
    • Call Win32 API directly
      • Simplest
      • Doesn’t require native DLL
      • Limited marshalling support
    • Calling native DLL
      • Enables custom marshalling
      • Native DLL can
        • Call APIs with complex arguments
        • Call COM interfaces
  • 26. Calling Win32 Functions
    • Finding the API
    • Declaring the API
    • Calling the API
  • 27. Finding the Win32 Function
    • Understand the difference between the Pocket PC and an embedded Windows CE device
      • Pocket PCs are based on Windows CE
        • Contain some unique APIs
        • Don’t support every single Windows CE API
      • Embedded Windows CE devices can have different APIs
        • Check the specific SDK for that device
  • 28. Declaring External Functions
    • Function to call should be declared with matching parameters
      • Function must be marked
        • “ static” and “extern” in C#
        • DllImport attribute
    • [DllImport( “coredll.dll" )]
      • public static extern unsigned int GetTickCount ();
  • 29. External Functions in VB
    • VB .NET function declaration
      • Use Lib keyword to declare external function
    Declare Function GetTickCount Lib "coredll.dll" () _ As Integer
  • 30. External Function Prototypes
    • Check documentation
      • Pocket PC 2000 and 2002
        • Need Embedded Visual C++ 3.0
      • Windows Mobile 2003
        • Need Embedded Visual C++ 4.0
    • Look in .h files in SDK
      • SDKs available on Microsoft’s web site
  • 31. Which DLL?
    • Windows CE API DLL is COREDLL.DLL
      • Almost everything is here
    • Some other DLLs are used
      • AYGShell.dll – Pocket PC shell functions
      • CommCtrl.dll – Common control lib
      • WinSock.dll – Windows Sockets
      • Phone.dll – High level phone control
      • SMS.dll – SMS messaging API
  • 32. Using DllImport
    • DllImport attribute class parameters
      • EntryPoint – Specifies different native function name
      • SetLastError – Maintains last error value
    [DllImport ( "indowsnManaged.dll" , EntryPoint= "TestProcW" , SetLastError= true )] public static extern int TestProc ( int a, byte [] b);
  • 33. At Runtime
    • Calling function causes the CLR:
      • Load the DLL using LoadLibrary
      • Use GetProcAddress to get entry point
      • Call the function
    • Problems resolving the function results in MissingMethodException in managed application
      • Unhandled exceptions in the unmanaged code results in app termination
  • 34. Tips for using P/Invoke
    • Isolate P/Invoke calls to custom classes
    • Make P/Invoke functions private
    • Public functions call P/Invoke functions in try / catch wrapper
      • This also allows parameter checking and necessary marshaling
  • 35. Data Marshaling
    • Simple Types
      • Direct Translation
    • Simple Objects and ValueTypes
      • Objects that contain simple types
      • Execution engine points at the data of the object
      • Some exceptions
    • Complex Objects and Value Types
      • Objects containing other objects need to manually marshal data
  • 36. Marshaling Differences
    • Objects marshaled only one level deep
      • Objects that contain objects must be manually marshaled
    • Datatypes are marshaled according to type
      • MarshalAs attribute is not supported
  • 37. Marshaling Differences 2
    • Object data is always laid out sequentially
      • StructLayout attribute is not used
      • Packing always set to 4
    • Floating point and 64-bit integer parameters need to be passed in as binary data
    • Cannot use delegates with native code
  • 38. Marshaling Of Simple Types
    • The execution engine marshaling of simple data types
    *bool and Boolean do NOT always convert to a Win32 BOOL Not Supported (floating pont) Double double Not Supported (64-bit) Long long wchar (16-bit) Char char BYTE (8-bit) * Boolean bool Data of the Array int * Array Integer () Array int [] wchar * String String short (16-bit) Short short int (32-bit integer) Integer int Native Code Visual Basic C#
  • 39. Marshaling Simple Objects *Execution Engine will resize managed strings after native function call Marshaling Action Parameter Type Point at the member data Other objects Make a copy of the string and point at the data (LPSTR) ByRef String* Point at the string data (LPSTR) String Make a copy and point at the string data (LPSTR) String Builder* Point at the array data Array
  • 40. Marshaling Simple Objects
    • Classes are laid out sequentially
      • Packing always set to 4
    • Only classes containing simple types will be automatically marshaled
    public class Rect { int left; int top; int right; int bottom; } Native Code - C C# typedef struct _RECT { LONG left; LONG top; LONG right; LONG bottom; } RECT;
  • 41. Marshaling Complex Objects
    • Marshal class
      • Located in System.Runtime.InteropServices
      • Provides advanced functionality to customize marshaling
    • Allows you to get copy managed objects into native code
    • Allows you to read and write raw memory if needed
    • When all else fails use byte array
  • 42. Classic P/Invoke Areas
    • The registry API
    • Interprocess communication
    • Managing very large memory blocks
    • Anything hardware related
    • Anything with a COM Interface
      • Obex, Pocket Outlook (POOM), …
  • 43. Writing Native DLLs
    • Standard Windows CE dll
    • Created with Embedded Visual C++
    • CPU specific
      • Need a version for each CPU supported
    • Beware C++ name mangling
    • Callable functions must be exported
  • 44. Tips for Writing Native DLLs
    • Use Extern “C”
      • Simplifies your exported function name
    • Depends.exe and Dumpbin /Exports are your friend
    • Test with a simple native application
      • Make sure the DLL loads properly
      • Make sure the function is exposed as you expected
  • 45. Limitations
    • Functions in DLLs should not block for long periods of time
    • DLLs can’t call into managed code
      • Events must be signaled using window messages
  • 46. Code Example
  • 47. External Events
    • How can a .NET CF application be notified of external events?
    • MessageWindow class
      • CF unique class for external event reporting
      • Basically, it’s a window that exposes its WndProc to the managed code
      • Helper methods to send/post messages to other windows
  • 48. MessageWindow Class
    • Apps can send and receive window messages
    • Messages have two 32 bit parameters
    • No support for marshaling data pointed to by window parameters
  • 49. MessageWindow Class
    • SendMessage Sends a message
    • PostMessage Posts a message
    • Hwnd Handle to native window
    • WndProc Override to receive messages sent to window
  • 50. Using MessageWindow
    • Derive class from MessageWindow
    • Override the WndProc method
    • Interpret window messages as necessary events
      • Use WM_USER+x
  • 51. Using MessageWindow
    • Pass window handle of MessageWindow class to native DLL
    • When native DLL detects event, use SendMessage to send WM_USER+x message to MessageWindow class
    • When MessageWindow derived class receives message, fire event to signal ‘other’ managed code.
  • 52. Compact Framework 2.0
  • 53. V2 .NET CF Improvements
    • Performance improvements
      • Better JIT’er
      • Often used paths optimized
    • XML Serialization
      • Schema  XSD  C# Classes
    • XML Schemas
    • XPath
    • SQL CE Result Set
      • Typed direct access to SQL CE database
      • Works with DataBinder
  • 54. V2 .NET CF Improvements
    • Improved support for COM interop
      • Runtime Callable wrappers
      • Improved marshalling support
        • More types
        • Embedded arrays
        • MarshalAs attribute
    • Additional controls supported
      • Web Browser Doc List
      • Date/Time Picker Rich Ink
      • Month Calendar Splitter
      • Link Label Data Container
      • Notification Bubble
    • Control’s window handle exposed
  • 55. V2 Language Improvements
    • Compact Framework picks up the improvements to the C# compiler scheduled for Visual Studio 2005
      • Generics
      • Anonymous methods
      • Partial Classes
    • VB developers get the My* namespace
  • 56. V2 Base Class Library Improvements
    • Serial Port Class
    • Registry Class
    • Cryptology Classes
    • Clipboard
    • Messaging
  • 57. New XML/Database Support
    • XML Serialization
      • Schema  XSD  C# Classes
    • XML Schemas
    • XPath
    • SQL CE Result Set
      • Typed direct access to SQL CE database
      • Works with DataBinder
  • 58. Summary
    • Try to avoid interop
    • Calling native code is fairly straightforward
    • Use eVC help and “Where defined”
    • Export unmangled DLL functions
    • Remember you’re still on Windows CE
    • 2.0 looks cool
  • 59. Suggested Reading And Resources
    • Visit the Microsoft Press Kiosk today to receive 40% off books purchased from Amazon.com
    • Microsoft Press books are available at the TechEd Bookstore and also at the Ask the Experts area in the Expo Hall
    The tools you need to put technology to work! TITLE Available Price Today $59.99 Programming Microsoft Windows CE .NET ®
  • 60. Questions [email_address] www.bolingconsulting.com