Upcoming SlideShare
Loading in...5







Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

CFInterop CFInterop Presentation Transcript

  • Compact Framework Interop Douglas Boling President Boling Consulting Inc. [email_address]
  • 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
  • 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
    View slide
  • Integration Imperative Web Applications Client Partner Partner Credit info Ad-hoc Screen scrape Email FAX B2C website HTML View slide
  • Integration Imperative Screen Scrape Client Website HTML
  • 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
  • .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
    • 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
  • 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
  • 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
  • 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
  • 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!
  • 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
  • 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
  • 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
  • .NET CF Size
    • Approximately 1.3 Mbytes on Pocket PC (ARM)
    • Needs approximately 1 Meg of RAM
    • Application sizes quite small
      • 5 – 100k
  • .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
  • .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
  • .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
  • 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
  • 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
  • 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
  • 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
    • 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
  • 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
  • Calling Win32 Functions
    • Finding the API
    • Declaring the API
    • Calling the API
  • 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
  • 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 ();
  • External Functions in VB
    • VB .NET function declaration
      • Use Lib keyword to declare external function
    Declare Function GetTickCount Lib "coredll.dll" () _ As Integer
  • 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
  • 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
  • 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);
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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#
  • 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
  • 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;
  • 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
  • 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), …
  • 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
  • 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
  • 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
  • Code Example
  • 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
  • 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
  • MessageWindow Class
    • SendMessage Sends a message
    • PostMessage Posts a message
    • Hwnd Handle to native window
    • WndProc Override to receive messages sent to window
  • Using MessageWindow
    • Derive class from MessageWindow
    • Override the WndProc method
    • Interpret window messages as necessary events
      • Use WM_USER+x
  • 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.
  • Compact Framework 2.0
  • 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
  • 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
  • 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
  • V2 Base Class Library Improvements
    • Serial Port Class
    • Registry Class
    • Cryptology Classes
    • Clipboard
    • Messaging
  • 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
  • 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
  • Suggested Reading And Resources
    • Visit the Microsoft Press Kiosk today to receive 40% off books purchased from
    • 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 ®
  • Questions [email_address]