Microsoft.NET Framework Interop Brian Long Master Consultant Falafel Software.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Advertisements

Ahead of Time Dynamic Translation PreJit/NGEN by any other name George Bosworth Microsoft MRE04 March 21, 2004.
By Sam Nasr September 28, 2004 Understanding MSIL.
Introduction to .NET Framework
Using.NET Platform Note: Most of the material of these slides have been taken & extended from Nakov’s excellent overview for.NET framework, MSDN and wikipedia.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
SSCLI: The Microsoft Shared Source CLI Implementation Mark Lewin Microsoft Research
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 1.1 of…
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Why COM and.Net? Jim Fawcett CSE775 – Distributed Objects Spring 2005.
Introducing the Common Language Runtime for.NET. The Common Language Runtime The Common Language Runtime (CLR) The Common Language Runtime (CLR) –Execution.
Introducing the Common Language Runtime. The Common Language Runtime The Common Language Runtime (CLR) The Common Language Runtime (CLR) –Execution engine.
2. Developing in.NET and C#. 2 Microsoft Objectives “Microsoft.NET development is based on an underlying framework of tools and classes. These tools and.
Creating and Running Your First C# Program Svetlin Nakov Telerik Corporation
Tahir Nawaz Visual Programming C# Week 2. What is C#? C# (pronounced "C sharp") is an object- oriented language that is used to build applications for.
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
.NET On A Shoe String By: Patrick Brannen Lead Developer iDevCo, Inc.
Intro to dot Net Dr. John Abraham UTPA – Fall 09 CSCI 3327.
A Free sample background from © 2001 By Default!Slide 1.NET Overview BY: Pinkesh Desai.
Lecture Roger Sutton CO530 Automation Tools 5: Class Libraries and Assemblies 1.
.NET Framework Introduction: Metadata
Introduction to .Net Framework
Sponsored by Powered by Moving at the Speed of Change May 2015 Charlotte PowerBuilder Conference Using.Net Nonvisual Assemblies In Powerbuilder Classic.
1 8/29/05CS360 Windows Programming Professor Shereen Khoja.
The Metadata System1. 2 Introduction Metadata is data that describes data. Traditionally, metadata has been found in language- specific files (e.g. C/C++
Session 1 - Introduction and Data Access Layer
Meir Botner David Ben-David. Project Goal Build a messenger that allows a customer to communicate with a service provider for a fee.
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#.
Microsoft.NET Vs Sun JAVA
 Internet providing backbone for applications  Use of several web sites and devices to provide one complete solution  Software as services  Quick software.
Understanding Code Compilation and Deployment Lesson 4.
Creating and Running Your First C# Program Svetlin Nakov Telerik Corporation
Lesley Bross, August 29, 2010 ArcGIS 10 add-in glossary.
Obsydian OLE Automation Ranjit Sahota Chief Architect Obsydian Development Ranjit Sahota Chief Architect Obsydian Development.
ASSEMBLY. A SSEMBLY Assemblies are the fundamental units of applications in the.net framework An assembly can contain classes, structures, interfaces.
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.
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
Bruce Armstrong TeamSybase
MSIL & CLI Kun-Yuan Shieh.
DEV331 Visual C++: Using The.NET Framework In Win32/MFC Applications Kate Gregory Gregory Consulting Limited.
Lecture 2 COM - Example. Integrate the web Webcam functionality using.Net and COM First let's explain what we should do exactly. First let's explain what.
Ni.com Understanding COM/ActiveX Jeff Paulter Staff Software Engineer Thurs Aug 17 10:15-11:30 a.m., 1:45-3:00 p.m. Ash (10A) Jeff Paulter Staff Software.
Component Services Tom Perkins - CertSIG. Software Component (Definition) A software component is a system element that –Offers a predefined service –Is.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
tom perkins1 XML Web Services -.NET FRAMEWORK – Part 1 CHAPTER 1.1 – 1.3.
PerlNET: The Camel Talks.NET Jan Dubois The Perl Conference 6 San Diego, July 26 th 2002.
Object Oriented Software Development 4. C# data types, objects and references.
DEV 420 Head-Spinning C++ Managed-Native Interoperability Kate Gregory Gregory Consulting.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
.NET Mobile Application Development XML Web Services.
INTRODUCTION CHAPTER #1 Visual Basic.NET. VB.Net General features It is an object oriented language  In the past VB had objects but focus was not placed.
July 22, 2001Introduction to.NET1 Introduction to.NET Framework Gholamali Semsarzadeh July 2001.
Text Introduction to.NET Framework. CONFIDENTIAL Agenda .NET Training – Purpose  What is.NET?  Why.NET?  Advantages  Architecture  Components: CLR,
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Pyragen A PYTHON WRAPPER GENERATOR TO APPLICATION CORE LIBRARIES Fernando PEREIRA, Christian THEIS - HSE/RP EDMS tech note:
Component Object Model
Component Object Model
Jim Fawcett CSE775 – Distributed Objects Spring 2017
An Introduction to the Shared Source Common Language Infrastructure (SSCLI) Damien Watkins Copyright Watkins 2002.
Native / Managed Interop
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
.NET and .NET Core 2. .NET Runtimes Pan Wuming 2017.
Introduction to C# AKEEL AHMED.
Programming in C# CHAPTER 1
Module 10: Implementing Managed Code in the Database
C# COM Interoperability
Presentation transcript:

Microsoft.NET Framework Interop Brian Long Master Consultant Falafel Software

.NET Interoperability Why Interoperability? The.NET platform is new The Win32 platform is well established No one wants to start from scratch Use of existing code in.NET applications is essential Interoperability goes both ways

.NET clients can use: Win32 COM server objects (RCW) Win32 DLL exports (P/Invoke) Win32 COM clients can use:.NET objects (CCW) Win32 clients can use:.NET method exports (Inverse P/Invoke) Interoperability Options

COM is dead!!! COM code equals legacy code If you don’t know COM, don’t start learning it now Er,.... That’s not practical There is a massive investment in COM that we still need to use COM

COM ↔.NET Interoperability is usually called Com Interop COM/Win32 ↔.NET requires marshaling of parameters COM Interop requires some reconciliation of COM reference counting and.NET GC mechanisms Interoperability requires some proxy / thunk / wrapper to be in place (automated) General Points

RCW – Runtime Callable Wrappers:.NET wrapper around COM object Type library importer (TlbImp.exe) generates an Interop Assembly Delphi 8 & “Diamondback” IDEs do it just as well Interop Assemblies have a common naming convention: Interop.LibraryName.dll (LibraryName is the type library name, not the COM server name).NET → COM (RCW)

Let’s make an Interop Assembly.NET → COM (RCW)

Use Primary Interop Assembly if available Primary Interop Assemblies are provided and signed by the COM component’s creator E.g. adodb.dll for MDAC objects Microsoft Office XP Primary Interop Assemblies available from MSDN web site.NET → COM (RCW)

RCW manages COM object reference count COM object is released during RCW garbage collection RCW turns HRESULTs into.NET exceptions.NET → COM (RCW)

A coclass Foo becomes an RCW FooClass Interfaces keep the same name An additional interface Foo is generated, combining the coclass’ default interface and a helper interface for the default event interface An event method Bar from an event interface IEvents gets turned into a delegate type IEvents_BarEventHandler. These COM events can be hooked up like normal.NET events.NET → COM (RCW)

Early binding: Straightforward - get an interface reference from the construction of the RCW Call methods or access properties Exposed events can be set up just like normal.NET events.NET → COM (RCW)

Let’s see some RCW early binding.NET → COM (RCW)

If the type library importer does not provide appropriate parameter type marshaling you can tweak it using creative round tripping Little other choice exists.NET → COM (RCW)

Late binding: This is possible without the Interop Assembly Uses reflection to operate New instance ( CreateOleObject ) through: –System.Type.GetTypeFromProgID –Activator.CreateInstance Current instance ( GetActiveOleObject ) through: –Marshal.GetActiveObject Note System.Reflection.Missing and System.Type.Missing (for EmptyParam ).NET → COM (RCW)

Late binding: Methods invoked through –System.Type.InvokeMember Parameters passed in an object array.NET → COM (RCW)

Let’s see some RCW late binding.NET → COM (RCW)

Late binding: Reference parameters are fiddly Overloaded InvokeMember requires single element array of ParameterModifier ParameterModifier is an array of Boolean flags Flag is True for reference parameter Flag is False for value parameter.NET → COM (RCW)

Let’s see some more RCW late binding.NET → COM (RCW)

Let’s see RCW early binding with events.NET → COM (RCW)

CCW – COM Callable Wrappers: COM wrapper around.NET object Assembly registration utility (RegAsm.exe) COM →.NET (CCW)

CCW ensures it will be marked for garbage collection when external reference count reaches 0 CCW turns.NET exceptions into HRESULTs Assembly must be accessible to CLR: –installed in GAC –resident in application directory (or available for probing) COM →.NET (CCW)

Late binding simply requires the assembly to be registered Late binding uses a ProgID registered by RegAsm.exe: AssemblyName.ClassName (e.g. MyAssembly.MyClass) COM →.NET (CCW)

Let’s see some CCW late binding COM →.NET (CCW)

Early binding relies on an Interop Type Library: –use the /tlb option with RegAsm –use the import wizard in “Diamondback”.NET objects may choose to implement a defined interface or not The Guid attribute can be used to give a.NET interface an IID (traditional Delphi syntax should also work*) *And does in “Diamondback”, but not in Delphi 8 COM →.NET (CCW)

The ClassInterface attribute controls whether and how an interface will be manufactured to expose the class: –AutoDispatch - dispinterface for late binding (the default) –AutoDual – for early binding (versioning issues) interface is class name with _ prefix –None – IDispatch access only Use AutoDual if you have no interface Use None if you implement an interface (the suggested approach to avoid interface versioning issues) COM →.NET (CCW)

Importing a Delphi assembly’s Interop Type Library requires some forethought, due to the symbols exposed by default Use [assembly: ComVisible(False)] and [ComVisible(True)] to control default visibility Early binding from Win32 uses the creator class in the type library import unit, as usual, or any of the other standard options COM →.NET (CCW)

Let’s see some CCW early binding COM →.NET (CCW)

.NET → Win32 (P/Invoke) Platform Invocation Service, usually referred to as Platform Invoke, or simply P/Invoke (or even PInvoke): DllImport attribute (from System.Runtime.InteropServices) is needed for routines with text parameters Standard Delphi DLL import syntax works otherwise Uses DllImport behind the scenes Caveat is string parameters

.NET → Win32 (P/Invoke) Let’s see a traditional import

.NET → Win32 (P/Invoke) //Win32 procedure FooA(Msg: PChar); cdecl; begin MessageBox(0, Msg, 'Foo', MB_OK or MB_ICONQUESTION); end; //.NET procedure Foo(const Msg: String);... [DllImport('bar.dll', EntryPoint = 'FooA', CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] procedure Foo(const Msg: String); external;

.NET → Win32 (P/Invoke) The big issue with P/Invoke is ensuring the parameters are marshaled across correctly. String parameters are generally catered for with DllImport.CharSet: –Ansi –None –Unicode –Auto * * uses Ansi on Win9x and Unicode on NT platforms

.NET → Win32 (P/Invoke) Let’s see some P/Invoke imports

.NET → Win32 (P/Invoke) Use Windows.pas and Delphi.Vcl.Windows.pas as guidelines for parameter type translation MarshalAs parameter attribute from System.Runtime.InteropServices Used to fix parameter marshaling when the default marshaling is inappropriate

.NET → Win32 (P/Invoke) Let’s see P/Invoke imports in use

.NET → Win32 (P/Invoke) Other issues surround Win32 error codes: –DllImport.SetLastError –Marshal.GetLastWin32Error –GetLastError HResult values: –safecall (Win32 COM) –DllImport.PreserveSig (.NET)

.NET → Win32 (P/Invoke) Let’s use P/Invoke attribute fields

.NET → Win32 (P/Invoke) Performance: P/Invoke calls cost ~10 machine instructions Cost rises for each extra job (marshaling etc.) By default security is on UnmanagedCode permission SuppressUnmanagedCodeSecurity attribute omits security check stack walk

.NET → Win32 (P/Invoke) Let’s see more P/Invoke code

.NET → Win32 (P/Invoke) New in Delphi “Diamondback” Virtual Library Interfaces (VLI) aka Dynamic PInvoke Makes a set of functions implemented in a DLL look like an interface implemented by an object Uses new overload of Supports

.NET → Win32 (P/Invoke) Let’s see some VLI

Win32 →.NET methods Little known mechanism (Inverse P/Invoke), primarily discussed in: –Inside Microsoft.NET IL Assembler, Serge Lidin, Microsoft Press Uses method transition thunks Only supported by Managed C++ and IL Oh, and Delphi for.NET

Win32 →.NET methods Very trivial mechanism in Delphi: managed exports Simply use an exports clause as you do in Win32 when exporting functions from DLLs Caveats: –Must mark the project source as containing unsafe code: {$UNSAFECODE ON} –Can only export “global” routines –Can not export static class methods this way

Win32 →.NET methods Can also be accomplished in other languages Much more involved (as indeed it is when exposing Delphi static class methods) Involves creative round-tripping to expose assembly methods

Win32 →.NET methods Round-tripping: Disassemble a compiled assembly to an IL source file with the.NET disassembler: ildasm.exe Modify the IL code, or add additional IL files, possibly to include features not supported by the original compiler Reassemble the IL code with the.NET assembler: ilasm.exe

Win32 →.NET methods Creative round-tripping: Disassemble a compiled assembly to an IL source file with the.NET disassembler: ildasm.exe Modify the IL code, or add additional IL files, possibly to include features not supported by the original compiler Reassemble the IL code with the.NET assembler: ilasm.exe

Win32 →.NET methods Let’s see some round tripping

Win32 →.NET methods IL modifications to export.NET methods: Modify IL manifest: –Modify.corflags directive to cater for XP issue –Declare a v-table fixup table –Declare data space for the v-table fixup table Modify implementations of methods to be exported: –Mark each method with the.vtentry and.export directives

Win32 →.NET methods IL file assembly manifest (original):.module dotNetAssembly.dll.imagebase 0x subsystem 0x file alignment 512.corflags 0x

Win32 →.NET methods IL file assembly manifest (modified):.module dotNetAssembly.dll.imagebase 0x subsystem 0x file alignment 512.corflags 0x data VT_01 = int32[2].vtfixup [2] int32 fromunmanaged at VT_01

Win32 →.NET methods Two IL methods (original):.method public static void DoSomething( int32 I) cil managed {.maxstack 1 IL_0000: ldarg.0 // rest of code omitted for brevity } // end of method Unit::DoSomething.method public static void DoSomethingElse( [in] string Msg) cil managed {.maxstack 1 IL_0000: ldarg.0 // rest of code omitted for brevity } // end of method Unit::DoSomethingElse

Win32 →.NET methods Two IL methods (exported):.method public static void DoSomething( int32 I) cil managed {.vtentry 1:1.export [1] as DoSomething.maxstack 1 IL_0000: ldarg.0 // rest of code omitted for brevity } // end of method Unit::DoSomething.method public static void DoSomethingElse( [in] string Msg) cil managed {.vtentry 1:2.export [2] as DoSomethingElse.maxstack 1 IL_0000: ldarg.0 // rest of code omitted for brevity } // end of method Unit::DoSomethingElse

Win32 →.NET methods Let’s see some creative round tripping

Win32 →.NET methods Potential maintenance issue: must modify IL generated from disassembling every built executable Workaround is a utility to automate the process (perhaps a command-line utility) One such utility (almost) is mme.exe (Managed Method Exporter) * mme.exe is actually a simple GUI app * supplied with source in the files that accompany this session

Everything you ever wanted to know about COM Interop (and lots you didn’t): References

The book to have in order to learn about Delphi 8 and the Microsoft.NET Framework: References

Full coverage of CIL (or MSIL) by the author of ILASM, ILDASM & the CLR Metadata validation engine

Questions?

Thank You 3222 Microsoft.NET Framework Interop Please fill out the speaker evaluation You can contact me further at