.NET.NET Interoperability Liran Ben Haim

Slides:



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

P/Invoke Made Easy Wei-Chen Wang.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Things to Remember When Developing 64-bit Software OOO "Program Verification Systems"
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Best Practices for Interop with Visual C++ Boris Jabes Program Manager Microsoft Corporation.
P/Invoke Made Easy Wei-Chen Wang. Marshaling governs how data is passed between managed and unmanaged memory during platform invoke. Function Call Interop.
Using Java interop in your Xamarin.Android
C#: Data Types Based on slides by Joe Hummel. 2 UCN Technology: Computer Science Content: “.NET is designed around the CTS, or Common Type System.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
AP 08/01 Component Programming with C# and.NET 1st Class Component Support Robust and Versionable Creating and using attributes API integration –DLL import.
Session 1 CS-240 Data Structures Binghamton University Dick Steflik.
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
3. Data Types. 2 Microsoft Objectives “.NET is designed around the CTS, or Common Type System. The CTS is what allows assemblies, written in different.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
.NET Framework & C#.
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
Chapter 2: Everything is an Object ● C++ has many non object oriented features inherited from C. It is a hybrid language meaning that it support different.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Leveraging.NET in SalesLogix Building Customizations in.NET for your Current Version of SalesLogix and a Look at the Future Ryan Farley Customer FX Corporation.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Introduction to C # – Part 2 Stephen Turner Software Design Engineer Microsoft UK.
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
Advanced C# Eric Gunnerson Program Manager Visual C#.NET Microsoft Corporation.
Effective C# 50 Specific Ways to Improve Your C# Item 46~ /09/25 1.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Module 14: Attributes. Overview Overview of Attributes Defining Custom Attributes Retrieving Attribute Values.
Microsoft Office Excel 2007: Programming Business Intelligence Features John Hooper Service Line Architect Microsoft Corporation Jed Farr Senior Consultant.
.NET Mobile Application Development Messaging & Communication from Mobile Devices.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
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.
Rachana George.NET Security, Summer Introduction Sample Unmanaged C++ Library Retrieve Exported Information from the DLL Perform Platform Invoke.
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.
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
Announcements There is a Quiz today. There were problems with grading assignment 2, but they should be worked out today The web page for correcting the.
Quick Summary C++/CLI Basics Data Types Controls Arrays In-class assignments.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 5 th Lecture Pavel Ježek
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
OE-NIK HP Advanced Programming Using and creating DLL files.
Pyragen A PYTHON WRAPPER GENERATOR TO APPLICATION CORE LIBRARIES Fernando PEREIRA, Christian THEIS - HSE/RP EDMS tech note:
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 3 rd Lecture Pavel Ježek
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Jim Fawcett CSE775 – Distributed Objects Spring 2009
Advanced .NET Programming II 4th Lecture
Native / Managed Interop
Interface Definition Language
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
Jim Fawcett CSE687 – Object Oriented Design Spring 2016
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Developing a Simple Graphical User Interface (GUI)
Jim Fawcett CSE687 – Object Oriented Design Spring 2009
CSC 253 Lecture 8.
CSC 253 Lecture 8.
AVG 24th 2015 ADVANCED c# - part 1.
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
C# COM Interoperability
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2006
Presentation transcript:

.NET.NET Interoperability Liran Ben Haim

2 Agenda Overview Overview  P/invoke  COM interop Performance Performance What’s new in.NET framework 2.0 What’s new in.NET framework 2.0 Questions Questions

3 Overview Platform Invoke   Finding and invoking unmanaged functions   Marshaling managed arguments to and from unmanaged code COM Interoperability   Runtime Callable Wrapper (RCW)   Used by managed clients to call a method on a COM object   COM Callable Wrapper (CCW)   Used by COM clients to call a method on a managed object

4 Win32 API / C DLL using System; using System.Runtime.InteropServices; class PlatformInvokeTest { [DllImport("msvcrt.dll")] [DllImport("msvcrt.dll")] public static extern int puts(string c); public static extern int puts(string c); [DllImport("msvcrt.dll")] [DllImport("msvcrt.dll")] internal static extern int _flushall(); internal static extern int _flushall(); public static void Main() public static void Main() { puts("Test"); puts("Test"); _flushall(); _flushall(); }}

5 C++ DLL (not COM) Create a MC++ class library Create a MC++ class libraryOr Add 2 global functions: Add 2 global functions:  Create object  Destroy object Use dumpbin.exe to extract the required member functions Use dumpbin.exe to extract the required member functions Use CallingConvention.ThisCall Use CallingConvention.ThisCall

6 Example class SAMP_API Csamp { int x; public: int getnum(void){return x;} void setnum(int x1){x=x1;} }; extern "C" Csamp SAMP_API *createobject() {return new Csamp;} extern "C" void SAMP_API deleteobject(Csamp *p) {delete p;} {delete p;}

7 [ DllImport( "samp.dll", CallingConvention=CallingConvention.ThisCall )] CallingConvention=CallingConvention.ThisCall )] public static extern int getnum( IntPtr ths); [ DllImport( "samp.dll", CallingConvention=CallingConvention.ThisCall )] CallingConvention=CallingConvention.ThisCall )] public static extern void setnum( IntPtr ths,int n); [ DllImport( "samp.dll" )] public static extern IntPtr createobject(); [ DllImport( "samp.dll" )] public static extern void deleteobject(IntPtr p);

8 Using the object IntPtr p=Class1.createobject(); Class1.setnum(p,77); MessageBox.Show(Class1.getnum(p). ToString()); Class1.deleteobject(p);

9 Creating Creating RCW Adding reference to a COM component in VS.NET IDE Adding reference to a COM component in VS.NET IDE Tlbimp.exe Tlbimp.exe  Tlbimp mycom.dll Custom wrapper Custom wrapper  Using reflection

10 Custom wrapper example Type excel; object[] parameter= new object[1]; object excelObject; excel = Type.GetTypeFromProgID("Excel.Application"); excelObject = Activator.CreateInstance(excel); parameter[0] = true; excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);

11 Creating CCW Tlbexp.exe Tlbexp.exe Regasm.exe Regasm.exe Register for com interop in VS.NET IDE Register for com interop in VS.NET IDE

12 Marshaling Governs how data is passed between managed and unmanaged memory during calls Governs how data is passed between managed and unmanaged memory during calls Most data types require no conversion Most data types require no conversion  byte  short  int  long  …

13 Custom marshaling [DllImport("msvcrt.dll")] public static extern int puts( [MarshalAs(UnmanagedType.LPStr)] [MarshalAs(UnmanagedType.LPStr)] string m); string m); Or use Marshal class Or use Marshal class

14 Marshal class C++ C++ typedef struct _MYSTRSTRUCT2 { char* buffer; UINT size; } MYSTRSTRUCT2; void TestOutArrayOfStructs(int* pSize, MYSTRSTRUCT2** ppStruct); void TestOutArrayOfStructs(int* pSize, MYSTRSTRUCT2** ppStruct);

15 [ StructLayout( LayoutKind.Sequential)] public class MyStruct { public String buffer; public int size; } [ DllImport( "..\\LIB\\PinvokeLib.dll" )] public static extern void TestOutArrayOfStructs( out int size, outIntPtr outArray );

16 int size; IntPtr outArray; LibWrap.TestOutArrayOfStructs( out size, out outArray ); MyStruct[] manArray = new MyStruct[ size ]; IntPtr current = outArray; for( int i = 0; i < size; i++ ) { manArray[ i ] = new MyStruct(); Marshal.PtrToStructure( current, manArray[ i ]); Marshal.DestroyStructure( current, typeof(MyStruct) ); current = (IntPtr)((int)current + Marshal.SizeOf( manArray[ i ] )); } Marshal.FreeCoTaskMem( outArray );

17 Using unsafe code [ StructLayout( LayoutKind.Sequential )] public struct MyUnsafeStruct { public IntPtr buffer; public int size; } [ DllImport( "..\\LIB\\PinvokeLib.dll" )] public static extern void TestOutArrayOfStructs( out int size, MyUnsafeStruct** outArray );

18 public static unsafe void UsingUnsafe() { int size; MyUnsafeStruct* pResult; LibWrap.TestOutArrayOfStructs( out size, &pResult ); MyUnsafeStruct* pCurrent = pResult; for( int i = 0; i < size; i++, pCurrent++ ) { Console.WriteLine( "Element {0}: {1} {2}", i, Marshal.PtrToStringAnsi( pCurrent->buffer ), pCurrent->size ); Marshal.FreeCoTaskMem( pCurrent->buffer ); } Marshal.FreeCoTaskMem( (IntPtr)pResult ); }

19 Transition performance With every transition from managed to unmanaged code (and vice versa) there is some performance overhead With every transition from managed to unmanaged code (and vice versa) there is some performance overhead Platform invoke call: Platform invoke call:  10 machine instructions (approx) + data marshaling time COM interop call: COM interop call:  50 machine instructions + data marshaling Make Chunky Calls Make Chunky Calls

20 String vs. individual chars typedef struct _OSVERSIONINFOA { DWORD dwOSVersionInfoSize; DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; CHAR szCSDVersion[ 10 ]; } OSVERSIONINFOA, *POSVERSIONINFOA, *LPOSVERSIONINFOA;

21 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] class OSVersionInfo { public UInt32 OSVersionInfoSize = (UInt32) Marshal.SizeOf(typeof(OSVersionInfo)); public UInt32 MajorVersion = 0; public UInt32 MinorVersion = 0; public UInt32 BuildNumber = 0; public UInt32 PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public String CSDVersion = null; }

22 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal struct OSVersionInfoBlittable { public UInt32 OSVersionInfoSize; public UInt32 MajorVersion; public UInt32 MinorVersion; public UInt32 BuildNumber; public UInt32 PlatformId; unsafe public String CSDVersion { get { fixed (Char* str = &CSDVersion0) { return new String(str); } }} Char CSDVersion0; Char CSDVersion1; Char CSDVersion2; Char CSDVersion3; Char CSDVersion4; Char CSDVersion5; Char CSDVersion6; Char CSDVersion7; Char CSDVersion8; Char CSDVersion9; }

23 Performance tips If you can find a.NET type that satisfies your needs, make use of it If you can find a.NET type that satisfies your needs, make use of it Primitive types require almost no marshaling at all Primitive types require almost no marshaling at all Translations from ASCII to Unicode are expensive Translations from ASCII to Unicode are expensive

24 Example - MessageBox 2 functions: 2 functions:  MessageBoxA - ansi  MessageBoxW – unicode [ DllImport( "User32.dll", EntryPoint="MessageBoxW", CharSet=CharSet.Unicode, ExactSpelling=true )] public static extern int MsgBox( int hWnd, String text, String caption, uint type );

25 Marshaling value types vs. reference types Marshaling Value types is preferable Marshaling Value types is preferable Managed structures are somewhat more similar to C structures than are managed classes Managed structures are somewhat more similar to C structures than are managed classes The runtime never reorganize the field layout of managed structures The runtime never reorganize the field layout of managed structures The GC never moves unboxed values around in memory The GC never moves unboxed values around in memory

26 SetLastError field [ DllImport( "User32.dll", SetLastError=true )] public static extern int MessageBox( IntPtr hWnd, String text, String caption, int type ); False in c# False in c# True in VB.NET True in VB.NET Use Marshal.GetLastWin32Error(); Use Marshal.GetLastWin32Error(); Use FormatMessage() API Use FormatMessage() API

27 Design Design Considerations Design chunky interfaces to avoid round trips. Reduce round trips with a facade. Implement IDisposable if you hold unmanaged resources across client calls. Reduce or avoid the use of late binding and reflection.   In ASP.NET – Server.CreateObject or Server.CreateObjectFromClsid

28 More guidelines Use IntPtr for manual marshaling. Use [in] and [out] to avoid unnecessary marshaling. [DllImport("gdi32.dll", CharSet=CharSet.Auto)] public static extern int CreateFontIndirect( [In, MarshalAs(UnmanagedType.LPStruct)] LOGFONT lplf );

29 Use SuppressUnmanagedCode for performance-critical trusted scenarios [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity] public static extern bool Beep(int frequency, int duration); Allows managed code to call into unmanaged code without a stack walk TLBIMP /unsafe   disable the full CAS stack walk for the unmanaged code Code Access Security

30 More info Improving.NET Application Performance and Scalability Improving.NET Application Performance and Scalability us/dnpag/html/scalenetchapt07.asp us/dnpag/html/scalenetchapt07.asp

31 New In.NET Framework 2.0 C++/CLI will include some useful templates for simplifying C++ interop C++/CLI will include some useful templates for simplifying C++ interop The new SafeHandle class, provide safe and reliable means of manipulating operating system handles The new SafeHandle class, provide safe and reliable means of manipulating operating system handles use with: [MethodImpl(MethodImplOptions.MustRun)]

32 The ability to wrap native function pointers into delegates The ability to wrap native function pointers into delegates  Marshal.GetDelegateForFunctionPointer  Marshal.GetFunctionPointerForDelegate The ability to marshal fixed-size arrays of structures inside structures The ability to marshal fixed-size arrays of structures inside structures [module: DefaultCharSet(CharSet.Auto)] [module: DefaultCharSet(CharSet.Auto)] Marshaling improvements