The Future of C++ on .NET: a Tour of C++/CLI
Total Page:16
File Type:pdf, Size:1020Kb
Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI The Future of C++ on .NET A Tour of C++/CLI Herb Sutter Architect Microsoft Visual C++ Quake II Takeaways 960x720 + software-rendered on 1.2GHz PIII-M + Fx 1.1.4322 1. It’s easy to run existing C/C++ code on .NET: 100% JITted (IL) code; still native data. • Just rebuild with /clr. • 1 day to port the entire Quake 2 source base. (Nearly all of the effort was to translate from C to C++, and had nothing to do with our compiler or the .NET platform.) 2. It’s not hard to extend existing code with CLR types. • 2 days to implement the radar extension using Fx (gradient brushes, window transparency/opacity, Matrix.RotateAt). 3. It needs to be still easier, more natural, and “first-class” to use C++ on the CLR. 2 Presented to NWCPP December 10, 2003 1 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI Overview 1. Rationale and Goals 2. Language Tour 3. Design and Implementation Highlights • Unified pointer and storage system (stack, native heap, gc heap). • Deterministic cleanup: Destruction/Dispose, finalization. • Generics × templates, STL on CLR. • Mixing native/CLR, other features. 4. C++/CLI Standardization • Venue, players, timelines, how to participate. 3 Microsoft’s Bet on .NET Windows XP SP1 (and onward): .NET ships in the OS Windows Longhorn: .NET is the OS API (WinFX) (.NET) WinFX builds on the .NET Framework Single crosscross-language-language framework for Windows 4 Presented to NWCPP December 10, 2003 2 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI Microsoft’s Bet on .NET Windows Longhorn: .NET is the OS API (WinFX) Presentation Data CommunicationCommunication Windows Windows ASP.NET ADO.NET Collaboration AvalonAvalonFormsForms WinFS Indigo Indigo Models DocumentDocument UIUI Media ObjectObject T/SQLT/SQL XMLXML ServiceService Schemas Desktop Desktop Window Controls Interop Adaptive UI Services Connectivity Messaging Desktop Desktop Window Controls Interop Adaptive UI People and ServicesServices Manager EngineEngine EngineEngine PeoplePeople GroupGroup ObjectSpacesObjectSpaces Services People and Channels PolicyPolicy GroupsGroups Channels Engine SynchronizationSynchronization CalendarCalendar Media (Datagram,(Datagram, Reliable,Reliable, Engine QueuingQueuing PresentationPresentation DesktopDesktop ApplicationApplication Page/SitePage/Site (WinFS,(WinFS, Win32..)Win32..) Peer,Peer, …)…) ObjectObject ManagerManager CompositionComposition EngineEngine ServicesServices CompositionComposition DocumentDocument … Channel CollaborationCollaboration DataSetDataSet Channel EventingEventing SecuritySecurity HistoryHistory Media Services InfoAgentInfoAgent Data Model TransportTransport ChannelsChannels Routing Message Routing (PreferenceRules..)(PreferenceRules..) (IPC,(IPC, HTTP,HTTP, TCP…)TCP…) Real-TimeReal-Time Items SQL XML Encoder Framework AnimationAnimation andand Media CaptureCapture andand DesignerDesigner PersonalizationPersonalization andand Items SQL XML Encoder Activities CompositionComposition ProcessingProcessing SourcingSourcing ServicesServices ProfilingProfiling ServicesServices System Services Activities RelationshipsRelationships FileSystemFileSystem Services Services Transaction CommunicationsCommunications ManagerManager Transaction HardwareHardware SoftwareSoftware RenderingRendering Membership and (MetaDataHandlers..)(MetaDataHandlers..) ProvidersProviders Signaling ControlsControls ExtensionsExtensions (Port)(Port) Signaling RenderingRendering andand SinksSinks SecuritySecurity ServicesServices FederationFederation CLR BaseBase ClassClass LibrariesLibraries Base Operating NetworkNetwork ClassClass LibraryLibrary System Services ApplicationApplication DeploymentDeployment Memory Manager CodeCode ExecutionExecution LoaderLoader SecuritySecurity SerializationSerialization EngineEngine (Click-Once)(Click-Once) HostingHosting LayerLayer Network Services DemandDemand ActivationActivation andand ProtocolProtocol HealthHealth Native TCP UDP IPC Direct 3D Management PNRPPNRP Native SIPSIP TCP UDP IPC Global Direct 3D Transactions Storage Management WiFi ListenerListener ListenerListener ListenerListener Window Global GraphicsGraphics ServicesServices GDI/GDI+GDI/GDI+ AudioAudio Lightweight Transaction Virtual Shadow File Replication Virtual Disk (Event Logs, Manager Engine Lightweight Transaction Virtual Shadow File Replication Virtual Disk (Event Logs, Engine GraphicsGraphics driversdrivers TransactionsTransactions CoordinatorCoordinator CopyCopy ServiceService ServiceService ServiceService Tracing,Tracing, InternetInternet ConnectionConnection FirewallFirewall Probes,Probes, Identity & Kernel Identity & AutoAuto Update,Update, DirectXDirectX Kernel Logging SecuritySecurity DistributedDistributed FilterFilter Admin) Protocols DDI InputInput AudioAudio Graphics TransactionTransaction Logging RedirectorsRedirectors Admin) DDI Manager DriversDrivers Graphics ServiceService SystemSystem FileFile SystemSystem Manager Mini port Manager Cache Filter TCP, UDP HTTP Cache Filter TCP, UDP IPSECIPSEC QOSQOS HTTP Manager EngineEngine IPV4,IPV4, IPV6IPV6 ListenerListener Security UniversalUniversal Plug and Memory Power Config Process Security LPC TransactedTransacted Kernel Mode Plug and Memory Power Config Process Reference LPC NTFS DataData FATFAT 16/3216/32 IO Manager Play Manager Manager Manager Manager Reference Facility NTFS Format IO Manager Play Manager Manager Manager Monitor Facility Format Device Drivers KernelKernel SCSI/FCSCSI/FC 802.3802.3 802.11802.11 .... HardwareHardware AbstractionAbstraction LayerLayer 5 .NET (aka CLI) Cross-Platform Microsoft .NET: WinFX, PocketPC, SPOT: • Windows XP SP1 and onward: .NET ships in the OS. • Windows Longhorn: .NET is the OS API (WinFX). • PocketPC and SPOT devices (.NET Compact Framework). Microsoft Rotor: • SSCLI: Shared-source implementation of ISO CLI. For non-commercial use. • Runs today on Windows XP, Mac OS X, and FreeBSD. Novell (Ximian) Mono: • First two commercial releasesreleases due Q2 2004 and Q4 2004. • Runs on Unix and Linux. Targets x86 and PowerPC directly. Targets Arm, Sparc, HPPA, and s390 via interpreter. • Includes ISO CLI, ASP.NET, ADO.NET, and GNOME- and Linux-specific libraries. 6 Presented to NWCPP December 10, 2003 3 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI ““v1v2””:: ManagedRevised Syntax Extensions (aka C++/CLI) Deterministic cleanup, Garbage collection, destructors. Garbage collection, finalizers. Templates. Generics. Native types. Reference and value types. Multiple inheritance. Interfaces. STL, generic algorithms, C++ CLRVerifiability. C++lambda expressions. CLR Security. Pointer/pointee distinction. Security. Properties, delegates, Copy construction, Properties, delegates, events. assignment. events. 7 Rationale C++: First-class .NET development language. • Remove “Why Can’t I” usability and migration barriers: Port and extend existing prprogramsograms even more seamlessly. • Key Q: “Why should a .NET developer use C++?” • Deliver promise of CLR. "Managed C++" insufficient: Grafting vs. integration. • Great for basic interop, migrating existing code to .NET. • Poor exposure of CLR features (e.g., __property). Poor integration of C++ and CLR featuresfeatures (e.g., no templates of CLR types). Hard to write pure (verifiable, secure) .NET apps. • Ugly and nonintuitive syntax, uneven and contorted semantics. Failed to achieve a natural, organic, “everything in its place” surfacing of features. • Low adoption. And those who do adopt still need to hand- wire way too much. 8 Presented to NWCPP December 10, 2003 4 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI Major Goals Feature coverage: • Provide organic support for CLR features/idioms. • Make sure they have a first-class feel. – Example: Verifiability at first try in this complete program: int main() { System::Console::WriteLine( "Hello, world!" ); } • Leave no room for a language lower than C++. C++ × CLR: Why a .NET programmer should use C++. • "Bring C++ to .NET": Support C++’s powerful features also for CLR types (e.g., deterministicdeterministic cleanup, templates). • "Bring .NET to C++": Support the CLR’s powerful features also for native types (e.g., verifiability, garbage collection). 9 Overview 1. Rationale and Goals 2. Language Tour 3. Design and Implementation Highlights • Unified pointer and storage system (stack, native heap, gc heap). • Deterministic cleanup: Destruction/Dispose, finalization. • Generics × templates, STL on CLR. • Mixing native/CLR, other features. 4. C++/CLI Standardization • Venue, players, timelines, how to participate. 10 Presented to NWCPP December 10, 2003 5 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI adjective class C; 11 Basic Class Declaration Syntax Type are declared “adjective class”: class N{ /*…*/ }; // native ref class R { /*…*/ }; // CLR reference type value class V { /*…*/ }; // CLR value type interface class I { /*…*/ }; // CLR interface type enum class E { /*…*/ }; // CLR enumeration type • C++ & .NET fundamental types are mapped to each other (e.g., int and System::Int32 are the same type). Examples: ref class A abstract { }; // abstract even w/o pure virtuals ref class B sealed : A { }; // no further derivation is allowed ref class C : B { }; // error, B is sealed 12 Presented to NWCPP December 10, 2003 6 Herb Sutter The Future of C++ on .NET: A Tour of C++/CLI Properties Basic syntax: ref class R { int mySize; public: property int Size { int get() { return mySize; } void set( int val ) { mySize = val; } } }; R r; r.Size = 42; //