COM Interop 允許 COM 開發人員像訪問其他 COM 對象一樣輕松訪問托管代碼。本教程說明如何將 C# 服務器與 C++ COM 客戶端一起使用。它還解釋了下列活動:
該教程還簡要說明了在托管和非托管組件之間自動應用的封送處理。
COM Interop 第一部分:C# 客戶端教程顯示使用 C# 與 COM 對象交互操作的基礎知識,這是該教程的前提。有關兩個教程的概述,請參見 COM Interop 教程。
該教程說明下列創建 C# 服務器的活動:
該教程還說明下列創建 COM 客戶端的活動:
注意 若要為導出到 COM 客戶端的接口和 coclass 創建 GUID,請使用 Guidgen.exe 工具,此工具是作為 Visual Studio 的一部分交付的。Guidgen 使您可以選擇 GUID 的表示格式,這樣您就不必重新鍵入它。有關 Guidgen 的更多信息,請參見知識庫文章 Q168318“XADM: Guidgen.exe Available Only for Intel Platforms”。知識庫文章可以在 MSDN Library 中以及 Web 站點 http://support.microsoft.com 上找到。
本示例由兩個文件組成:
// CSharpServer.cs// compile with: /target:library// post-build command: regasm CSharpServer.dll /tlb:CSharpServer.tlbusing System;using System.Runtime.InteropServices;namespace CSharpServer{ // Since the .NET Framework interface and coclass have to behave as // COM objects, we have to give them guids. [Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")] public interface IManagedInterface { int PrintHi(string name); } [Guid("C6659361-1625-4746-931C-36014B146679")] public class InterfaceImplementation : IManagedInterface { public int PrintHi(string name) { Console.WriteLine("Hello, {0}!", name); return 33; } }}
// COMClient.cpp// Build with "cl COMClient.cpp"http:// arguments: friend#include <windows.h>#include <stdio.h>#pragma warning (disable: 4278)// To use managed-code servers like the C# server, // we have to import the common language runtime:#import <mscorlib.tlb> raw_interfaces_only// For simplicity, we ignore the server namespace and use named guids:#if defined (USINGPROJECTSYSTEM)#import "..\RegisterCSharpServerAndExportTLB\CSharpServer.tlb" no_namespace named_guids#else // Compiling from the command line, all files in the same directory#import "CSharpServer.tlb" no_namespace named_guids#endifint main(int argc, char* argv[]){ IManagedInterface *cpi = NULL; int retval = 1; // Initialize COM and create an instance of the InterfaceImplementation class: CoInitialize(NULL); HRESULT hr = CoCreateInstance(CLSID_InterfaceImplementation, NULL, CLSCTX_INPROC_SERVER, IID_IManagedInterface, reinterpret_cast<void**>(&cpi)); if (FAILED(hr)) { printf("Couldn't create the instance!... 0x%x\n", hr); } else { if (argc > 1) { printf("Calling function.\n"); fflush(stdout); // The variable cpi now holds an interface pointer // to the managed interface. // If you are on an OS that uses ASCII characters at the // command prompt, notice that the ASCII characters are // automatically marshaled to Unicode for the C# code. if (cpi->PrintHi(argv[1]) == 33) retval = 0; printf("Returned from function.\n"); } else printf ("Usage: COMClient <name>\n"); cpi->Release(); cpi = NULL; } // Be a good citizen and clean up COM: CoUninitialize(); return retval;}
可以用以下命令行調用可執行客戶端:COMClient <name>
,其中 <name>
表示要使用的任何字符串,如 COMClient friend
。
Calling function.Hello, friend!Returned from function.
在示例 IDE 項目中,將項目“屬性頁”中的“命令行參數”屬性設置為需要的字符串(例如,“friend”)。