DEV 420 Head-Spinning C++ Managed-Native Interoperability Kate Gregory Gregory Consulting.

Slides:



Advertisements
Similar presentations
DEV351 ADO.NET Performance Pablo Castro Program Manager – ADO.NET Team Microsoft Corporation.
Advertisements

Best Practices for Interop with Visual C++ Boris Jabes Program Manager Microsoft Corporation.
.NET Framework Overview Pingping Ma Nov 16 th, 2006.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation Namespaces Simple Make Files (Ignore all class references.
Thursday Evening 6.30VB.NET Introduction 7.30Break for food 8.00VB.NET Migration 8.45Q & A 9.00Done.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Why COM and.Net? Jim Fawcett CSE775 – Distributed Objects Spring 2005.
Review of C++ Programming Part II Sheng-Fang Huang.
OFC302 Building Smart Document Solutions in Word & Excel Martin Sawicki Lead Program Manager.
A Free sample background from © 2001 By Default!Slide 1.NET Overview BY: Pinkesh Desai.
McGraw-Hill© 2007 The McGraw-Hill Companies, Inc. All rights reserved. 1-1.
Lecture Roger Sutton CO530 Automation Tools 5: Class Libraries and Assemblies 1.
DEV334 Creating Application Starting Points & Sharing Best Practices with Enterprise Templates Marc Gusmano Director of Emerging Technologies The Information.
Introduction to .Net Framework
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
CIS NET Applications1 Chapter 2 –.NET Component- Oriented Programming Essentials.
.NET Framework & C#.
Appendix D: Microsoft.NET Framework Overview. Overview.NET Framework Architecture.NET Namespaces.
 Internet providing backbone for applications  Use of several web sites and devices to provide one complete solution  Software as services  Quick software.
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Working with Unmanaged Code.
Nilotpal Bhattacharya Partner Technical Consultant| Microsoft.
DEV290 Building Office Solutions with Visual Studio Eric Carter Lead Developer Developer Platform & Evangelism Microsoft Corporation.
ASSEMBLY. A SSEMBLY Assemblies are the fundamental units of applications in the.net framework An assembly can contain classes, structures, interfaces.
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
‘Tirgul’ # 7 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #7.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
DAT305 Boost Your Data-Driven Application Development Using SQL Server Centric.NET Code Generator Pascal Belaud Microsoft France.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
.NET Framework Danish Sami UG Lead.NetFoundry
DEV325 Deploying Visual Studio.NET Applications Billy Hollis Author / Consultant.
Namespaces Tonga Institute of Higher Education. Introduction to Namespaces The.Net Framework provides many classes for doing different things  File Input/Output.
DEV331 Visual C++: Using The.NET Framework In Win32/MFC Applications Kate Gregory Gregory Consulting Limited.
DEV339 Best Practices for Debugging Visual Studio.NET Applications Keith Pleas Architect, Guided Design
Monday, Jan 13, 2003Kate Gregory with material from Deitel and Deitel Week 2 Questions from Last Week Control Structures Functions Lab 1.
Sage ACT! 2013 SDK Update Brian P. Mowka March 23, 2012 Template date: October 2010.
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Effective C# 50 Specific Ways to Improve Your C# Item 46~ /09/25 1.
DEV337 Modeling Distributed Enterprise Applications Using UML in Visual Studio.NET David Keogh Program Manager Visual Studio Enterprise Tools.
tom perkins1 XML Web Services -.NET FRAMEWORK – Part 1 CHAPTER 1.1 – 1.3.
DEV333 Instrumenting Applications for Manageability with the Enterprise Instrumentation Framework David Keogh Program Manager Visual Studio Enterprise.
DEV303 ASP.NET: Leveraging Visual Studio.NET For Web Projects Tony Goodhew Product Manager Microsoft Corp.
VB6 Migration to.NET Sean Puffett Developer & Platform Group Microsoft Ltd
DEV330 Visual Studio.NET IDE Tips and Tricks Billy Hollis Author / consultant.
GAM666 – Introduction To Game Programming ● DirectX is implemented as a collection of COM objects ● To use a DirectX program, the user must have the correct.
MBL490 Deploying Applications to Smartphone and Microsoft® Powered Pocket PC Marcus Perryman Consultant.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
DEV395 No Touch Deployment for Windows Forms Jamie Cool Program Manager.NET Client Microsoft Corporation.
Tips & Tricks: Writing Performant Managed Code Rico Mariani FUNL04 Performance Architect Microsoft Corporation.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
1 Introduction to Object Oriented Programming Chapter 10.
Text Introduction to.NET Framework. CONFIDENTIAL Agenda .NET Training – Purpose  What is.NET?  Why.NET?  Advantages  Architecture  Components: CLR,
SQL Server 2005:.NET Framework Programming in the Database Tim Sneath Architectural Engineer, Microsoft
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Component Object Model
Component Object Model
Introduction to Web Assembly
Chapter 6 CS 3370 – C++ Functions.
Overview 4 major memory segments Key differences from Java stack
Jim Fawcett CSE775 – Distributed Objects Spring 2009
Abstract Data Types and Encapsulation Concepts
Overview 4 major memory segments Key differences from Java stack
Abstract Data Types and Encapsulation Concepts
Build /23/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Module 10: Implementing Managed Code in the Database
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2006
SPL – PS1 Introduction to C++.
Blazor A new framework for browser-based .NET apps Ryan Nowak
Presentation transcript:

DEV 420 Head-Spinning C++ Managed-Native Interoperability Kate Gregory Gregory Consulting

Too Much Choice? Millions of lines of C++ code already exist Business logic Proprietary algorithms Class libraries from long-dead vendors This code is not going anywhere It’s tested It works It’s paid for

Session Prerequisites Familiarity with the.NET Framework and the CLR Experience developing in Managed C++ Experience developing in unmanaged C++ MFC ATL Another compiler or class library Familiarity with COM concepts

Agenda Setting the stage COM Interop PInvoke It Just Works What should you do?

The Legacy class ArithmeticClass { public: double Add( double num1, double num2); };

Unmanaged application int _tmain(void) { ArithmeticClass arith; cout << "1 + 2 is " << arith.Add(1,2) << endl; return 0; }

Making the Legacy Available You’re writing a new Managed C++ application Or a VB.NET or C# application and you don’t mind it having some Managed C++ portions You want to use your legacy library You know there are tradeoffs Your effort Performance What else?

COM Interop Managed code can use a COM component as simply as a.NET object Runtime Callable Wrapper (RCW) looks like a.NET object on the outside, but inside it uses a COM component Holds GUIDs, progids etc Translates casts into QueryInterface, new into CoCreateInstance, etc Handles reference counting Can be generated automatically since a type library can map to an assembly’s metadata

How do you make an RCW? From Managed C++ project, add a reference Use the COM tab Produces a passable RCW automatically Marshals between COM and.NET types Handles QI and Reference Counting Turns HRESULTs into exceptions It is possible to write your own “Interop Assembly” if you really need to

Wrap the Legacy in COM ATL Project Add Simple ATL Object Retype method definitions into wizard Paste method bodies into project Could create a wrapper that called into a LIB or DLL

Using the COM Object #import "..\ComArithmetic\Debug\ComArithmetic.dll" no_namespace int _tmain(int argc, _TCHAR* argv[]) { ::CoInitialize(NULL); //braces for scope only { IArithmeticClassPtr arith("ComArithmetic.ArithmeticClass"); double answer = arith->Add(1,3); cout << "1 + 3 is " << answer << endl; cin.get(); } ::CoUninitialize(); return 0; }

Using COM from.NET int _tmain(void) { ComArithmetic::CArithmeticClassClass* arith = new ComArithmetic::CArithmeticClassClass(); double answer = arith->Add(2,3); Console::Write("2 + 3 is "); Console::WriteLine(__box(answer)); return 0; }

Wrap the Legacy as a DLL Win32 project, application type is DLL Pull member functions out of the class Add declspec to each extern "C" __declspec(dllexport) double Add(double num1, double num2) { return num1+ num2; }

Using the DLL from.NET using namespace System::Runtime::InteropServices; [DllImport("debug/dllarithmeticglobal.dll")] extern "C" double Add(double num1, double num2); int _tmain(void) { double answer = Add(4,3); Console::Write("4 + 3 is "); Console::WriteLine(__box(answer)); return 0; }

C++ Is Special If the Pinvoke defaults are fine with you, leave it out: extern "C" double Add(double num1, double num2); int _tmain(void) { double answer = Add(4,3); Console::Write("4 + 3 is "); Console::WriteLine(__box(answer)); return 0; }

Finding the DLL Add the import library to the dependencies

Finding the DLL Make sure the import library is on the linker dependency path Make sure the DLL is on the executable search path

C++ Is Special What is happening in this example? No Pinvoke Linking to a.lib that has unmanaged code Nothing special about the function declaration You can even use the.h file from the DLL project with __declspec(dllexport) in it, and the compiler just ignores the declspec It Just Works!

It Just Works If you have unmanaged code you want to compile as managed, just compile it It will compile It will run Even if it calls out to unmanaged code Statically linked Dynamically linked MFC ATL Whatever!

XCopy Porting Create a new managed application Copy the.cpp files and.h files into the project folder These create non-gc classes Probably call out to other libraries Use Add, Add Existing Item Now the code is in the project Build it!

XCopy Porting Builds to IL

A Mixed Exe File-by-file, you can request native code instead of IL May gain performance Give up being managed

A Mixed Exe Use the property pages for the file

A Mixed Exe You can also control managed or unmanaged compilation within a file: Before a function: #pragma unmanaged int foo(); Use with caution, it can confuse maintainers

Agenda Setting the stage COM Interop PInvoke It Just Works What should you do?

What Should You Do? Performance Maintenance Convenience and Development Time Security and Permissions

Performance Usually unmanaged code called from unmanaged code is the fastest solution Sometimes the xcopy port can surprise you XCopy port may get faster if you make individual files compile to native code DLL (with or without PInvoke) is slower than these two, but faster than COM It’s a trace faster without PInvoke COM Interop has the most overhead

Maintenance What other applications are using this code now? How do they call it? Crazy to maintain a COM component and a class library as separate copies Even if the class library does execute a bit faster under.NET Maybe some refactoring is the way to go in that case Pull functionality into a class library COM component and.NET component both use the class library

Developer Convenience This is all pretty easy, really Still, why run around refactoring or wrapping if you don’t need to? Hard to argue with It Just Works Avoid maintaining two sets of code, but don’t create wrappers for their own sake

Security Code Access Security Granular Permissions Access file system Make SQL connection Call unmanaged code Surely each of the ways of reusing legacy C++ code has different security implications?

Skip Verification By default, all C++ projects demand SkipVerification permission The IL doesn’t have to pass the Verifier checks All means all COM Interop Pinvoke XCopy port, 100 % IL Mixed EXE No security implications of the reuse choice

Verifiable Code Starting in Visual Studio.NET 2003, C++ projects can turn off the SkipVerification request, but they must be verifiable Hardly any C++ code will meet the requirements for verifiable code No pointer arithmetic No linking to unmanaged code (IJW), or #pragma unmanaged – no CRT PInvoke OK Optimizer off

Bottom Line If the code you want to reuse is not being used in any other application XCopy Port If the code is a COM Component now COM Interop If you notice a performance issue, refactor to a library and a COM component, and use the library from.NET If the code is a DLL now Use PInvoke if you need to control marshaling Otherwise IJW

What About VB and C#? They can only get to your old code through COM Interop or PInvoke But you can write a little wrapper class Managed (__gc) class in Managed C++ Wraps each method of the old class and calls it using IJW VB and C# can use language interop on the CLR to call these methods C++ provides the bridge to the old world Maximizes performance

Wrapper class public __gc class ArithmeticWrapper { private: ArithmeticClass* ac; public: ArithmeticWrapper() {ac = new ArithmeticClass();} double Add(double num1, double num2) {return ac->Add(num1,num2);} ~ArithmeticWrapper() {delete ac;} };

Why not make ArithmeticClass __gc? Can't allocate on stack Old code will break Can you delete a pointer to a garbage- collected class? Yes: ArithmeticWrapper* wrapper = new ArithmeticWrapper(); answer = wrapper->Add(5,6); delete wrapper;

Resources and Links My Code Guru Column MSDN msdn.microsoft.com/visualc/ GotDotNet

Community Resources Most Valuable Professional (MVP) Newsgroups Converse online with Microsoft Newsgroups, including Worldwide User Groups Meet and learn with your peers

evaluations evaluations

© 2002 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.