首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 托管代碼與 C++ 非托管代碼互相調用(二):C++ 調用 C# COM 組件(二)

     編輯:關於C語言

C++ 調用 C# COM 組件步驟

  1. 建立 C++ 專案:Win32 Console Application。
  2. 導入類型庫:#import "..\\Debug\\ComInteropDemo.tlb" (路徑需正確)。
  3. 初始化 COM、建立智慧指標、呼叫方法、釋放 COM。

C++ 完整代碼


#include "stdafx.h"
#include 
using namespace std;

#import "..\\Debug\\ComInteropDemo.tlb"

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr;
    CoInitialize(NULL);

    // 建立介面智慧指標
    ComInteropDemo::ComInteropInterfacePtr ptr;
    hr = ptr.CreateInstance(__uuidof(ComInteropDemo::ComInterop));

    if (hr == S_OK)
    {
        cout << ptr->Add(1.0, 2.0) << endl; // 輸出 3
    }

    CoUninitialize();
    return 0;
}

C# COM 組件建置關鍵 (回顧)

  • 介面與類別標註 [Guid]、[ComVisible(true)]。
  • 類別繼承 ServicedComponent,介面方法標註 [DispId]。
  • 專案啟用「註冊 COM 互通」與強命名簽章。
  • 使用 REGASM ComInteropDemo.dll /tlb ComInteropDemo.tlb 產生類型庫;重新建置前需 REGASM /u 解除註冊。

智慧指標優勢

_com_ptr_t (如 ComInteropInterfacePtr) 自動管理 AddRef/Release,避免記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved