Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

Exposing C# Objects to COM

Just as an RCW proxy wraps a COM object when you access it from C#, code that accesses a C# object as a COM object must do so through a proxy as well. When your C# object is marshaled out to COM, the runtime creates a COM Callable Wrapper (CCW). The CCW follows the same lifetime rules as other COM objects, and as long as it is alive, a CCW maintains a traceable reference to the object it wraps. This keeps the object alive when the garbage collector is run.

The following example shows how you can export both a class and an interface from C# and control the Global Unique Identifiers (GUIDs) and Dispatch IDs (DISPIDs) assigned. After compiling IRunInfo and StackSnapshot, you can register both using RegAsm.exe.

// IRunInfo.cs
// Compile with:
//   csc /t:library IRunInfo.cs
using System;
using System.Runtime.InteropServices;
[GuidAttribute("aa6b10a2-dc4f-4a24-ae5e-90362c2142c1")]
public interface IRunInfo {
  [DispId(1)]
  string GetRunInfo();
}
 
// StackSnapshot.cs
//   compile with csc /t:library /r:IRunInfo.dll StackSnapShot.cs
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
[GuidAttribute("b72ccf55-88cc-4657-8577-72bd0ff767bc")]
public class StackSnapshot : IRunInfo {
  public StackSnapshot() {
    st = new StackTrace();
  }
  [DispId(1)]
  public string GetRunInfo() {
    return st.ToString();
  }
  private StackTrace st;
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata