P/Invoke Made Easy Wei-Chen Wang. Marshaling governs how data is passed between managed and unmanaged memory during platform invoke. Function Call Interop.

Slides:



Advertisements
Similar presentations
P/Invoke Made Easy Wei-Chen Wang.
Advertisements

Introduction to C Programming
What's new in Microsoft Visual C Preview
Algorithms and data structures
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
.NET.NET Interoperability Liran Ben Haim
Best Practices for Interop with Visual C++ Boris Jabes Program Manager Microsoft Corporation.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Run time vs. Compile time
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
C and Data Structures Baojian Hua
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Memory Layout C and Data Structures Baojian Hua
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
Java Introduction to JNI Prepared by Humaira Siddiqui.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
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.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Object Oriented Software Development 4. C# data types, objects and references.
BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
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.
Announcements Partial Credit Due Date for Assignment 2 now due on Sat, Feb 27 I always seem to be behind and get tons of daily. If you me and.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 5 th Lecture Pavel Ježek
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
C++ Functions A bit of review (things we’ve covered so far)
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
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.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Object Lifetime and Pointers
Java Yingcai Xiao.
Static data members Constructors and Destructors
Advanced .NET Programming II 4th Lecture
Native / Managed Interop
COMPUTER 2430 Object Oriented Programming and Data Structures I
CSC 253 Lecture 8.
CSC 253 Lecture 8.
Memory Allocation CS 217.
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.
CISC/CMPE320 - Prof. McLeod
Pointers and References
Presentation transcript:

P/Invoke Made Easy Wei-Chen Wang

Marshaling governs how data is passed between managed and unmanaged memory during platform invoke. Function Call Interop Marshaling In Parameters Out Parameters Managed Client Unmanage d Library

Pass Parameters 3 ways to transfer parameters between managed code and unmanaged code 1.Marshaling the data by Marshaler 2.Allocating an unmanaged memory block, populating the data, and passing the address of the memory block 3.Just passing the address of the managed object without marshaling the object

The unsafe Way unsafe { IntPtr ms = Marshal.AllocHGlobal(sizeof(MyStruct)); MyStruct *pms = (MyStruct*)ms; ms->a = MAGIC_NUMBER; ms->str1 = Marshal.AllocHGlobal(MAGIC_STRING.length*2); strcpy( ms->str1, MAGIC_STRING); func( ms ); } /* C Declarations */ struct MyStruct { DWORD num; LPWSTR str1; } void func(struct MyStruct *ms); /* C# Wrapper */ struct MyStruct { Int32 num; IntPtr str1; } [DllImport("dll.dll")] void func(IntPtr ms); directly operate the object via pointer pass the address, IntPtr, of the struct

A Better Way { IntPtr pms = Marshal.AllocHGlobal(sizeof(MyStruct)); MyStruct ms; ms.num = MAGIC_NUMBER; ms.str1 = Marshal.StringToHGlobalUni(MAGIC_STRING); Marshal.StructureToPtr(ms, pms, false); func(ms); } /* C Declarations */ struct MyStruct { DWORD num; LPWSTR str1; } void func(struct MyStruct *ms); /* C# Wrapper */ struct MyStruct { Int32 num; IntPtr str1; } [DllImport("dll.dll")] void func(IntPtr ms); operate the managed object allocate memory and copy string by Mashaler utility

Summary, So Far... unsafe code is hard to write (in C#), hard to debug, and lack of compiling-time and runtime checking. In most case, we don't have to use unsafe pointers. We should operate everything on managed objects, and convert them to unmanaged objects only when we want to perform platform invoke. It is free to encapsulate the converting code as methods of the object. Methods won't change the memory layout of the object. Using AllocHGlobal to manually allocate an unmanaged memory block is necessary, if we want to pass the object for an asynchronous call.

Marshaling by Marshaler (the best way) { MyStruct ms; // operate on managed object ms.num = MAGIC_NUMBER; ms.str = MAGIC_STRING; // pass the object // the Marsahler will convert it to unmanaged object func(ref ms); } /* C Declarations */ struct MyStruct { DWORD num; LPWSTR str1; } void func(struct MyStruct *ms); /* C# Wrapper */ struct MyStruct { Int32 num; [MarshalAs(UnmanagedType.LPWStr)] String str1; } [DllImport("dll.dll")] void func(ref MyStruct ms); indicate the string should be converted to a pointer, which points to a string buffer

Marshaling Internals 9. Return from C# wrapper Heap Object Code Stack Heap Code Stack C# Wrapper()Function() 1. Call C# wrapper Object 2. Marshal managed In-parameters to native 3. Call native code Parameters 6. Clean up managed Out- parameters 7. Marshal native Out-parameters to managed Object 8. Clean up native data Managed Memory Unmanaged Memory 5. Return from native code 4. native code operate on unmanaged object

Default Marshaling for Blittable Types you best friend 8. Return from C# wrapper Heap Code Stack Heap Code Stack C# Wrapper()Function() 1. Call C# wrapper4. Call native code Parameters Object Managed Memory Unmanaged Memory 6. Return from native code 5. native code operate on managed object 2. Pin the object 3. Pass the address (call-by- reference) 7. Un-Pin the object

Delegate/Callback Heap Code Stack Code Stack delegate delegate() Managed Memory Unmanaged Memory callback() C# Wrapper()Function() 2. pass delegate marshaled as a function pointer 4. invoke callback Parameters 1. Call C# wrapper 7. Return from C# wrapper 3. Call native code 6. Return from native code 5. return from callback

ICustomMarshaler in Action Heap Object Code Stack Heap Code Stack C# Wrapper()Function() Object Parameters Object Managed Memory Unmanaged Memory 1. GetInstance() to get a instance of the marshaler 2. MarshalManaged ToNative() 3. CleanUp ManagedData() 3. Call/Return from native code 4. MarshalNative ToManaged() 5. CleanUp NativeData()

Windows String at A Glance ANSI String= char array=user locale encoding Unicode String= wchar array=UTF-16 Little-Endian (Unicode is not necessary UTF-16LE, but in Windows, it is) T-String= TCHAR array, char or wchar depends on compiling configuration WINUSERAPI int WINAPI MessageBoxA( __in_opt HWND hWnd, __in_opt LPCSTR lpText, __in_opt LPCSTR lpCaption, __in UINT uType); WINUSERAPI int WINAPI MessageBoxW( __in_opt HWND hWnd, __in_opt LPCWSTR lpText, __in_opt LPCWSTR lpCaption, __in UINT uType); #ifdef UNICODE #define MessageBox MessageBoxW #else #define MessageBox MessageBoxA #endif // !UNICODE

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct MyStruct { [MarshalAs(UnmanagedType.LPStr)] string str1; [MarshalAs(UnmanagedType.LPWStr)] string str2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = N)] string str3; } More on Marshaling String struct MyStruct { LPSTR str1; LPWSTR str2; WCHAR str3[N]; }; MyStruct ms; ms.str1 = "Hello"; ms.str2 = "world"; ms.str3 = "!!!"; function( ref ms); Just pass the struct. The marshaler will do the rest for you

Get a String Out void GetString( LPWSTR *text, int nMaxCount ); [DllImport("dll.dll")] static extern void GetString(StringBuilder text, int nMaxCount); 1 [DllImport("dll.dll")] static extern void GetString(out String text, int nMaxCount); 3 Don't Do It! Just Do It StringBuilder sbtext = new Stringbuilder(STR_LENGTH); GetString( sbtext, sbtext.Capacity ); The memory allocated on text in GetString() will leak. [DllImport("dll.dll")] static extern void GetString(ref String text, int nMaxCount); 2 Don't Do It Too You cannot specify the size of the output buffer. void GetString( LPWSTR text, int nMaxCount );

InAttribute and OutAttribute InAttribute indicates that data should be marshaled from the caller to the callee, but not back to the caller OutAttribute indicates that data should be marshaled from callee back to caller Use the proper attributes to reduce unnecessary data copy /* Example */ [DllImport("mydll.dll")] static extern void func([in] ref MyStruct); // pass the reference(pointer) of the structure // parameter will be copied in, but not out

Keep Objects in Memory Local variable can be garbage collected as it reach a point where it appears no longer being referenced // suppose WriteFile is a native function { File file = new File("file.txt"); IntPtr h = file.Handle; // file is eligible for finalization WriteFile( h ); // WriteFile( file.h ); doesn't help anything // file.WriteFile(); // Write a wrapper method in File and call // WriteFile in the method // This doesn't help too }

2 1 Solutions { File file = new File("file.txt"); IntPtr h = file.Handle; PInvoke(h); GC.KeepAlive(file); } { File file = new File("file.txt"); IntPtr h = file.Handle; GCHandle gh = GCHnalde.Alloc(file); PInvoke(h); gh.Free(); } 3 { File file = new File("file.txt"); IntPtr h = file.Handle; PInvoke(new HandleRef(file, h)); } The purpose of KeepAlive is to keep a reference the object. Besides that, KeepAlive have no side-effect. Allocating a GCHandle prevents the object from being collected. HandleRef guarantees that the object is not collected until the p/invoke completes

GCHandle GCHandle can be used to 1.prevent an objects being garbage collected 2.pin an object in memory, so it won't be relocated by GC (the object has to be of a value-type) 3.get the address of a pinned object

Pin an Object struct PinMe { int a; int b; } void PinYou() { struct PinMe pm; pm.a = MAGIC_NUM1; pm.b = MAGIC_NUM2; GCHandle gh = GCHandle.Alloc(pm, GCHandleType.Pinned); // manipulate the object in CFunction() CFunction(gh.AddrOfPinnedObject()); gh.Free(); } Only blittable object can be pinned. The only reason to pin an blittable object it that you want to pass it to unmanaged code for an asynchronous operation, hence you don't want GC relocate it.

Get the Handle of an Object void function() { Object obj = new Object(); GCHandle gh = GCHandle.Alloc(obj); CFunction( GCHandle.ToIntPtr(gh), Callback ); } void Callback(IntPtr p) { GCHandle gh = GCHandle.FromIntPtr(p); Object obj = gh.Target; gh.Free(); } We can't manipulate a managed object in unmanaged code, but we can pass the handle of it between managed and unmanaged code as callback data.

Default Marshaling for Blittable Types struct MyStruct { Int32 a; Int32 b; public MyStruct(Int32 _a, Int32 _b) { a = _a; b = _b; } } [DllImport("dll.dll")] void CFunction(ref MyStruct ms); MyStruct ms = new MyStruct(MAGIC_A, MAGIC_B); CFunction(ref ms); struct MyStruct { DWORD a; DWORD b; }; void f(struct MyStruct *ms);

Write Your Own Marshaler class MyClass { /*... */ } class MyClassMarshaler: ICustomMarshaler { public void CleanUpManagedData(object ManagedObj); public void CleanUpNativeData(IntPtr pNativeData); public IntPtr MarshalManagedToNative(object ManagedObj); public object MarshalNativeToManaged(IntPtr pNativeData); } [DllImport("dll.dll")] static extern void Function( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(MyClassMarshaler))] MyClass mc ); Custom marshaler used For marshaling MyClass Use MyClassMarshaler to marshal MyClass

References Interop Marshaling Marshaling Data with Platform Invoke Blittable and Non-Blittable Types HandleRef Structure us/library/system.runtime.interopservices.handleref.aspx SafeHandles: the best V2.0 feature of the.NET Framework SafeHandle: A Reliability Case Study The Truth About GCHandles GCHandle.ToIntPtr vs. GCHandle.AddrOfPinnedObject GCHandles, Boxing and Heap Corruption SafeHandle: A Reliability Case Study [Brian Grunkemeyer]