CFInterop
-
Upload
webuploader -
Category
Technology
-
view
2.043 -
download
0
description
Transcript of CFInterop
04/08/23
1
Compact Framework InteropCompact Framework Interop
Douglas BolingPresidentBoling Consulting [email protected]
2
About MeAbout Me
Independent Windows CE consultant Independent Windows CE consultant Microsoft Embedded MVPMicrosoft Embedded MVP
WriterWriter Author of “Programming Windows CE”Author of “Programming Windows CE” Various articlesVarious articles
Windows CE InstructionWindows CE Instruction Windows CE Application DevelopmentWindows CE Application Development Windows CE OAL and DriversWindows CE OAL and Drivers .NET Compact Framework.NET Compact Framework
www.bolingconsulting.comwww.bolingconsulting.com
3
AgendaAgenda
Quick intro to the Compact FrameworkQuick intro to the Compact Framework
What is Interop?What is Interop?
P/Invoke BasicsP/Invoke Basics
Marshalling Marshalling
Calling native DLLsCalling native DLLs
Notifications from outsideNotifications from outside
What’s coming in Version 2.0What’s coming in Version 2.0
4
Integration ImperativeIntegration Imperative
ClientClient
Web Web ApplicationsApplications
PartnerPartnerPartnerPartner
Credit Credit infoinfo
Ad-hocAd-hoc
ScreenScreenscrapescrape
FAXFAX
B2CB2Cwebsitewebsite
HTMLHTML
5
Integration ImperativeIntegration Imperative
ClientClient
WebsiteWebsite
HTMLHTML
Screen
Scrape
6
Windows XP EmbeddedWindows XP EmbeddedThe most complete embedded platform enabling advanced The most complete embedded platform enabling advanced devices by delivering the power of Windows in devices by delivering the power of Windows in componentized formcomponentized form
Windows CE Windows CE Windows CE integrates reliable real time capabilities with Windows CE integrates reliable real time capabilities with advanced Windows technologies to rapidly build a wide advanced Windows technologies to rapidly build a wide range of innovative, small-footprint devicesrange of innovative, small-footprint devices
Windows Embedded PlatformsWindows Embedded Platforms
7
.NET on Embedded Devices.NET on Embedded Devices
Windows XP EmbeddedWindows XP Embedded Full v1.0 .NET runtimeFull v1.0 .NET runtime
1.1 in SP21.1 in SP2 Total compatibilityTotal compatibility
Windows CE .NETWindows CE .NET Specially designed runtimeSpecially designed runtime Smaller foot printSmaller foot print Tuned for low memory, low power devicesTuned for low memory, low power devices Limited to two languagesLimited to two languages
C#, Visual Basic .NETC#, Visual Basic .NET
8
In short: .NET runtime for small devicesIn short: .NET runtime for small devices CLR + subset of FCLCLR + subset of FCL
1.0 supports1.0 supports Pocket PC 2000, 2002Pocket PC 2000, 2002 Windows Mobile 2003Windows Mobile 2003
Pocket PC and SmartphonePocket PC and Smartphone
Windows CE .NET 4.1 and laterWindows CE .NET 4.1 and later
2.0 supports2.0 supports Windows Mobile 2003 for Pocket PC onlyWindows Mobile 2003 for Pocket PC only Windows CE 5.0 and laterWindows CE 5.0 and later
.NET Compact Framework.NET Compact Framework
9
Get the Latest Stuff!Get the Latest Stuff!
Two service packs have been releasedTwo service packs have been released
Service Pack 1Service Pack 1 Bug fixesBug fixes
Service Pack 2Service Pack 2 Minor class library additionsMinor class library additions Performance improvementsPerformance improvements Bug fixesBug fixes
Version 2.0 in Whidbey betaVersion 2.0 in Whidbey beta
10
CF SimilaritiesCF Similarities
Same type safe executionSame type safe execution No uninitialized variablesNo uninitialized variables No unsafe castsNo unsafe casts No bad array indexingNo bad array indexing No bad pointer mathNo bad pointer math
Similar garbage collectionSimilar garbage collection No ref countingNo ref counting No leaksNo leaks
JIT compilation JIT compilation Compiled code kept in memoryCompiled code kept in memory Pitched in low memory situationsPitched in low memory situations
11
CF SimilaritiesCF Similarities
Exceptions for error handlingExceptions for error handling
Language neutral type systemLanguage neutral type system Common scheme across all managed codeCommon scheme across all managed code
Use of assembliesUse of assemblies
PE file formatPE file format
Mutithread supportMutithread support
Windows Forms supportWindows Forms support
Can consume web servicesCan consume web services
12
CF Difference StrategyCF Difference Strategy
V1 support for client processingV1 support for client processing Little support for devices as serversLittle support for devices as servers
Reduced resources on embedded devicesReduced resources on embedded devices Less CPU power/system memory renders some .NET features Less CPU power/system memory renders some .NET features
impracticalimpractical
CF Development scheduleCF Development schedule They had to ship!They had to ship!
13
CF DifferencesCF Differences
No COM interop supportNo COM interop support Use P/Invoke to call unmanaged functionsUse P/Invoke to call unmanaged functions Manually create managed class that P/Invokes to DLL that then Manually create managed class that P/Invokes to DLL that then
calls COM interfacescalls COM interfaces
No remoting No remoting Client web services supportedClient web services supported
No ASP .NETNo ASP .NET
No generic serializationNo generic serialization
No install time compilationNo install time compilation No nGenNo nGen
14
CF DifferencesCF Differences
No reflection emitNo reflection emit
Domain neutral code areas not supportedDomain neutral code areas not supported
Asynchronous delegates not supported Asynchronous delegates not supported
File change notifications not supportedFile change notifications not supported
No XML schema validationNo XML schema validation
No XML xpath queriesNo XML xpath queries
FCL SubsetFCL Subset
15
Other ChangesOther Changes
.NET CF Class library about 25% of desktop class library.NET CF Class library about 25% of desktop class library
Runtime tuned for embedded systemsRuntime tuned for embedded systems Low memory devicesLow memory devices Low power CPUsLow power CPUs
Extra classes addedExtra classes added IrDA classesIrDA classes SQLCE classesSQLCE classes Pocket PC control supportPocket PC control support MessageWindow classMessageWindow class
16
.NET CF Size.NET CF Size
Approximately 1.3 Mbytes on Pocket PC (ARM)Approximately 1.3 Mbytes on Pocket PC (ARM)
Needs approximately 1 Meg of RAMNeeds approximately 1 Meg of RAM
Application sizes quite smallApplication sizes quite small 5 – 100k5 – 100k
17
.NET Framework.NET FrameworkSystem.WebSystem.Web System.Windows.FormsSystem.Windows.Forms
System.DrawingSystem.Drawing
System.XMLSystem.XMLSystem.DataSystem.Data
SystemSystem
ServicesDescriptionDiscoveryProtocols
UIHTML ControlsWeb Controls
Security
Session StateConfiguration
Cache
SQL Client
SQL ServerCEDesign
ADO.NET
IO
Net
Collections
Security
Reflection
Resources
Text
Globalization
Configuration
Service Process
Diagnostics
Threading
RuntimeInterop ServicesRemotingSerialization
Design
Drawing 2D
Imaging
XML Document
Xslt/XPath
Serialization
Reader/Writers
Printing
Text
Component Model
18
.NET Compact Framework.NET Compact FrameworkSystem.WebSystem.Web System.Windows.FormsSystem.Windows.Forms
System.DrawingSystem.Drawing
System.XMLSystem.XMLSystem.DataSystem.Data
SystemSystem
ServicesDescriptionDiscoveryProtocols
UIHTML ControlsWeb Controls
Security
Session StateConfiguration
Cache
SQL Client
SQL ServerCEDesign
ADO.NET
IO
Net
Collections
Security
Reflection
Resources
Text
Globalization
Configuration
Service Process
Diagnostics
Threading
RuntimeInterop ServicesRemotingSerialization
Design
Drawing 2D
Imaging
XML Document
Xslt/XPath
Serialization
Reader/Writers
Printing
Text
Component Model
19
.NET CF Interop.NET CF Interop
Why important?Why important? The v1 release of .NET Compact Framework will not support The v1 release of .NET Compact Framework will not support
everything necessary for a Windows CE applicationeverything necessary for a Windows CE application
Even if it did, embedded devices frequently need to be closer to Even if it did, embedded devices frequently need to be closer to the hardware than PC applicationsthe hardware than PC applications
20
General Strategy General Strategy
Enable developers to provide their own solutionsEnable developers to provide their own solutions Decent P/Invoke supportDecent P/Invoke support COM ready managed threadsCOM ready managed threads
Basic support for notifying managed code of external eventsBasic support for notifying managed code of external events Somewhat of an afterthoughtSomewhat of an afterthought
21
General ArchitectureGeneral Architecture
Managed applications are managed as Windows CE processesManaged applications are managed as Windows CE processes Subject to the same limitations of a Windows CE processSubject to the same limitations of a Windows CE process
32/64 Meg memory space32/64 Meg memory space DLL issues in Pocket PC 2002DLL issues in Pocket PC 2002
Native DLLs are loaded into the process space of the managed Native DLLs are loaded into the process space of the managed applicationapplication
Unmanaged DLLs not loaded until called Unmanaged DLLs not loaded until called Call your unmanaged DLLs earlyCall your unmanaged DLLs early
22
What is SupportedWhat is Supported
Supported Supported Calling unmanaged functions in DLLsCalling unmanaged functions in DLLs
““P/Invoke” supportP/Invoke” support
UnsupportedUnsupported Directly calling COM interfacesDirectly calling COM interfaces
Only by calling unmanaged DLLs that deal with COM Only by calling unmanaged DLLs that deal with COM objectsobjects
ActiveX controlsActiveX controls Third party solution availableThird party solution available
23
Steps for Calling Native CodeSteps for Calling Native Code
Decide what you need to doDecide what you need to do
Look for a managed wayLook for a managed way Always choose the managed way before P/InvokeAlways choose the managed way before P/Invoke
Look in the SDK for the unmanaged callLook in the SDK for the unmanaged call Yes, you’ll still need to know the APIYes, you’ll still need to know the API
24
Create managed class to wrap P/Invoke callsCreate managed class to wrap P/Invoke calls
Declare an static, extern function with matching call Declare an static, extern function with matching call parametersparameters
Declare function as externalDeclare function as external C# – Mark with the DllImport attributeC# – Mark with the DllImport attribute VB .NET – Use Lib keywordVB .NET – Use Lib keyword
Create public methods that call P/Invoke methodsCreate public methods that call P/Invoke methods
Steps for Calling Native CodeSteps for Calling Native Code
25
Two General PossibilitiesTwo General Possibilities
Call Win32 API directlyCall Win32 API directly SimplestSimplest Doesn’t require native DLLDoesn’t require native DLL Limited marshalling supportLimited marshalling support
Calling native DLLCalling native DLL Enables custom marshallingEnables custom marshalling Native DLL can Native DLL can
Call APIs with complex argumentsCall APIs with complex arguments Call COM interfacesCall COM interfaces
26
Calling Win32 FunctionsCalling Win32 Functions
Finding the APIFinding the API
Declaring the APIDeclaring the API
Calling the APICalling the API
27
Finding the Win32 FunctionFinding the Win32 Function
Understand the difference between the Pocket PC and an Understand the difference between the Pocket PC and an embedded Windows CE deviceembedded Windows CE device
Pocket PCs are based on Windows CEPocket PCs are based on Windows CE Contain some unique APIsContain some unique APIs Don’t support every single Windows CE APIDon’t support every single Windows CE API
Embedded Windows CE devices can have different APIsEmbedded Windows CE devices can have different APIs Check the specific SDK for that deviceCheck the specific SDK for that device
28
Declaring External FunctionsDeclaring External Functions
Function to call should be declared with matching Function to call should be declared with matching parametersparameters
Function must be marked Function must be marked ““static” and “extern” in C#static” and “extern” in C# DllImport attributeDllImport attribute
[DllImport(“coredll.dll")]public static extern unsigned int GetTickCount ();
29
External Functions in VBExternal Functions in VB
VB .NET function declarationVB .NET function declaration Use Lib keyword to declare external functionUse Lib keyword to declare external function
Declare Function GetTickCount Lib "coredll.dll" () _As Integer
30
External Function PrototypesExternal Function Prototypes
Check documentation Check documentation Pocket PC 2000 and 2002Pocket PC 2000 and 2002
Need Embedded Visual C++ 3.0Need Embedded Visual C++ 3.0 Windows Mobile 2003Windows Mobile 2003
Need Embedded Visual C++ 4.0Need Embedded Visual C++ 4.0
Look in .h files in SDKLook in .h files in SDK SDKs available on Microsoft’s web siteSDKs available on Microsoft’s web site
31
Which DLL?Which DLL?
Windows CE API DLL is Windows CE API DLL is COREDLL.DLLCOREDLL.DLL Almost everything is hereAlmost everything is here
Some other DLLs are usedSome other DLLs are used AYGShell.dll – Pocket PC shell functionsAYGShell.dll – Pocket PC shell functions CommCtrl.dll – Common control libCommCtrl.dll – Common control lib WinSock.dll – Windows SocketsWinSock.dll – Windows Sockets Phone.dll – High level phone controlPhone.dll – High level phone control SMS.dll – SMS messaging APISMS.dll – SMS messaging API
32
Using DllImportUsing DllImport
DllImport attribute class parametersDllImport attribute class parameters EntryPoint – Specifies different native function nameEntryPoint – Specifies different native function name SetLastError – Maintains last error valueSetLastError – Maintains last error value
[DllImport ("\\windows\\UnManaged.dll", EntryPoint="TestProcW", SetLastError=true)]
public static extern int TestProc (int a, byte[] b);
33
At RuntimeAt Runtime
Calling function causes the CLR:Calling function causes the CLR: Load the DLL using LoadLibraryLoad the DLL using LoadLibrary Use GetProcAddress to get entry pointUse GetProcAddress to get entry point Call the functionCall the function
Problems resolving the function results in Problems resolving the function results in MissingMethodException in managed applicationMissingMethodException in managed application
Unhandled exceptions in the unmanaged code results in app Unhandled exceptions in the unmanaged code results in app termination termination
34
Tips for using P/InvokeTips for using P/Invoke
Isolate P/Invoke calls to custom classesIsolate P/Invoke calls to custom classes
Make P/Invoke functions privateMake P/Invoke functions private
Public functions call P/Invoke functions in try / catch wrapperPublic functions call P/Invoke functions in try / catch wrapper This also allows parameter checking and necessary marshaling This also allows parameter checking and necessary marshaling
35
Data MarshalingData Marshaling
Simple TypesSimple Types Direct TranslationDirect Translation
Simple Objects and ValueTypesSimple Objects and ValueTypes Objects that contain simple typesObjects that contain simple types Execution engine points at the data of the objectExecution engine points at the data of the object Some exceptionsSome exceptions
Complex Objects and Value TypesComplex Objects and Value Types Objects containing other objects need to manually marshal dataObjects containing other objects need to manually marshal data
36
Marshaling DifferencesMarshaling Differences
Objects marshaled only one level deepObjects marshaled only one level deep Objects that contain objects must be manually marshaledObjects that contain objects must be manually marshaled
Datatypes are marshaled according to typeDatatypes are marshaled according to type MarshalAs attribute is not supportedMarshalAs attribute is not supported
37
Marshaling Differences 2Marshaling Differences 2
Object data is always laid out sequentiallyObject data is always laid out sequentially StructLayout attribute is not usedStructLayout attribute is not used Packing always set to 4Packing always set to 4
Floating point and 64-bit integer parameters need to be passed Floating point and 64-bit integer parameters need to be passed in as binary datain as binary data
Cannot use delegates with native codeCannot use delegates with native code
38
Marshaling Of Simple TypesMarshaling Of Simple Types
The execution engine marshaling of simple data typesThe execution engine marshaling of simple data types
C#C# Visual BasicVisual Basic Native CodeNative Code
intint IntegerInteger int (32-bit integer)int (32-bit integer)
shortshort ShortShort short (16-bit)short (16-bit)
boolbool BooleanBoolean BYTE (8-bit)BYTE (8-bit)**
charchar CharChar wchar (16-bit)wchar (16-bit)
StringString StringString wchar *wchar *
Array Array
int []int []
ArrayArray
Integer ()Integer ()
Data of the ArrayData of the Array
int *int *
longlong LongLong Not Supported (64-bit)Not Supported (64-bit)
doubledouble DoubleDouble Not Supported (floating pont)Not Supported (floating pont)
*bool and Boolean do NOT always convert to a Win32 BOOL*bool and Boolean do NOT always convert to a Win32 BOOL
39
Marshaling Simple ObjectsMarshaling Simple Objects
Parameter TypeParameter Type Marshaling ActionMarshaling Action
ArrayArray Point at the array dataPoint at the array data
String Builder*String Builder* Make a copy and point at the string data Make a copy and point at the string data (LPSTR)(LPSTR)
StringString Point at the string data Point at the string data (LPSTR)(LPSTR)
ByRef String*ByRef String* Make a copy of the string and point at the Make a copy of the string and point at the data data (LPSTR)(LPSTR)
Other objectsOther objects Point at the member dataPoint at the member data
*Execution Engine will resize managed strings after native function call*Execution Engine will resize managed strings after native function call
40
public class Rect {
int left;int top;int right;int bottom;
}
Marshaling Simple ObjectsMarshaling Simple Objects
Classes are laid out sequentially Classes are laid out sequentially Packing always set to 4Packing always set to 4
Only classes containing simple types will be automatically Only classes containing simple types will be automatically marshaledmarshaled
Native Code - CC#
typedef struct _RECT {
LONG left; LONG top; LONG right; LONG bottom;
} RECT;
41
Marshaling Complex ObjectsMarshaling Complex Objects
Marshal classMarshal class Located in System.Runtime.InteropServicesLocated in System.Runtime.InteropServices Provides advanced functionality to customize marshalingProvides advanced functionality to customize marshaling
Allows you to get copy managed objects into native codeAllows you to get copy managed objects into native code
Allows you to read and write raw memory if neededAllows you to read and write raw memory if needed
When all else fails use byte arrayWhen all else fails use byte array
42
Classic P/Invoke AreasClassic P/Invoke Areas
The registry APIThe registry API
Interprocess communicationInterprocess communication
Managing very large memory blocksManaging very large memory blocks
Anything hardware relatedAnything hardware related
Anything with a COM InterfaceAnything with a COM Interface Obex, Pocket Outlook (POOM), … Obex, Pocket Outlook (POOM), …
43
Writing Native DLLsWriting Native DLLs
Standard Windows CE dllStandard Windows CE dll
Created with Embedded Visual C++Created with Embedded Visual C++
CPU specificCPU specific Need a version for each CPU supportedNeed a version for each CPU supported
Beware C++ name manglingBeware C++ name mangling
Callable functions must be exported Callable functions must be exported
44
Tips for Writing Native DLLsTips for Writing Native DLLs
Use Extern “C” Use Extern “C” Simplifies your exported function nameSimplifies your exported function name
Depends.exe and Dumpbin /Exports are your friendDepends.exe and Dumpbin /Exports are your friend
Test with a simple native applicationTest with a simple native application Make sure the DLL loads properlyMake sure the DLL loads properly Make sure the function is exposed as you expectedMake sure the function is exposed as you expected
45
Limitations Limitations
Functions in DLLs should not block for long periods of timeFunctions in DLLs should not block for long periods of time
DLLs can’t call into managed codeDLLs can’t call into managed code Events must be signaled using window messagesEvents must be signaled using window messages
46
Code ExampleCode Example
47
External EventsExternal Events
How can a .NET CF application be notified of external How can a .NET CF application be notified of external events?events?
MessageWindow classMessageWindow class CF unique class for external event reportingCF unique class for external event reporting
Basically, it’s a window that exposes its WndProc to the Basically, it’s a window that exposes its WndProc to the managed codemanaged code
Helper methods to send/post messages to other windowsHelper methods to send/post messages to other windows
48
MessageWindow ClassMessageWindow Class
Apps can send and receive window messagesApps can send and receive window messages
Messages have two 32 bit parametersMessages have two 32 bit parameters
No support for marshaling data pointed to by window No support for marshaling data pointed to by window parametersparameters
49
MessageWindow ClassMessageWindow Class
SendMessageSendMessage Sends a messageSends a message
PostMessagePostMessage Posts a messagePosts a message
HwndHwnd Handle to native windowHandle to native window
WndProcWndProc Override to receive messages Override to receive messages sent to windowsent to window
50
Using MessageWindowUsing MessageWindow
Derive class from MessageWindowDerive class from MessageWindow
Override the WndProc methodOverride the WndProc method
Interpret window messages as necessary eventsInterpret window messages as necessary events Use WM_USER+xUse WM_USER+x
51
Using MessageWindowUsing MessageWindow
Pass window handle of MessageWindow class to native DLLPass window handle of MessageWindow class to native DLL
When native DLL detects event, use SendMessage to send When native DLL detects event, use SendMessage to send WM_USER+x message to MessageWindow classWM_USER+x message to MessageWindow class
When MessageWindow derived class receives message, fire When MessageWindow derived class receives message, fire event to signal ‘other’ managed code.event to signal ‘other’ managed code.
52
Compact Framework 2.0Compact Framework 2.0
53
V2 .NET CF ImprovementsV2 .NET CF Improvements
Performance improvementsPerformance improvements Better JIT’erBetter JIT’er Often used paths optimizedOften used paths optimized
XML SerializationXML Serialization Schema Schema XSD XSD C# Classes C# Classes
XML SchemasXML Schemas
XPathXPath
SQL CE Result SetSQL CE Result Set Typed direct access to SQL CE databaseTyped direct access to SQL CE database Works with DataBinderWorks with DataBinder
54
V2 .NET CF ImprovementsV2 .NET CF Improvements
Improved support for COM interopImproved support for COM interop Runtime Callable wrappersRuntime Callable wrappers Improved marshalling supportImproved marshalling support
More typesMore types Embedded arraysEmbedded arrays MarshalAs attributeMarshalAs attribute
Additional controls supportedAdditional controls supported Web BrowserWeb Browser Doc ListDoc List Date/Time PickerDate/Time Picker Rich InkRich Ink Month CalendarMonth Calendar SplitterSplitter Link LabelLink Label Data ContainerData Container Notification BubbleNotification Bubble
Control’s window handle exposedControl’s window handle exposed
55
V2 Language ImprovementsV2 Language Improvements
Compact Framework picks up the improvements to the C# Compact Framework picks up the improvements to the C# compiler scheduled for Visual Studio 2005compiler scheduled for Visual Studio 2005
Generics Generics Anonymous methodsAnonymous methods Partial Classes Partial Classes
VB developers get the My* namespaceVB developers get the My* namespace
56
V2 Base Class Library ImprovementsV2 Base Class Library Improvements
Serial Port ClassSerial Port Class
Registry ClassRegistry Class
Cryptology ClassesCryptology Classes
ClipboardClipboard
Messaging Messaging
57
New XML/Database SupportNew XML/Database Support
XML SerializationXML Serialization Schema Schema XSD XSD C# Classes C# Classes
XML SchemasXML Schemas
XPathXPath
SQL CE Result SetSQL CE Result Set Typed direct access to SQL CE databaseTyped direct access to SQL CE database Works with DataBinderWorks with DataBinder
58
SummarySummary
Try to avoid interopTry to avoid interop
Calling native code is fairly straightforward Calling native code is fairly straightforward
Use eVC help and “Where defined”Use eVC help and “Where defined”
Export unmangled DLL functions Export unmangled DLL functions
Remember you’re still on Windows CERemember you’re still on Windows CE
2.0 looks cool2.0 looks cool
59
Suggested Reading And Resources
Visit the Microsoft Press Kiosk today to receive Visit the Microsoft Press Kiosk today to receive 40%40% off books off books purchased from Amazon.compurchased from Amazon.com
Microsoft Press books are available at the TechEd Bookstore Microsoft Press books are available at the TechEd Bookstore and also at the Ask the Experts area in the Expo Halland also at the Ask the Experts area in the Expo Hall
The tools you need to put technology to work!The tools you need to put technology to work!
TITLETITLE AvailableAvailable PricePrice
TodayToday $59.99$59.99Programming Microsoft Programming Microsoft Windows CE .NETWindows CE .NET®®