2017年2月5日 星期日

.NET C# 建立 COM元件 (4) --- VC++呼叫COM元件函數

在知道如何透過C#建立COM元件,那筆者也將VC++如何呼叫C#產生出來的COM DLL。
一樣使用前面的C#範例,來做一些修改。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace TestVBA
{
    [Guid("6EE994BA-95B5-4548-98CB-B87663557880")]
    public interface IVBAFunc
    {
        [DispId(1)]
        int Multiply(int a, int b);
    }

    [Guid("A4F15491-8F1B-49C3-B626-589ECBCC60E7")]
    [ClassInterface(ClassInterfaceType.None)] //表示沒有為該class產生COM介面
    [ProgId("TestVBA.VBAFunc")]
    public class VBAFunc : IVBAFunc
    {
        public int Multiply(int a, int b)
        {
            return a * b;
        }
    }
}
以VC++開一個TestCOM專案,輸入以下程式碼。
#include "TestCOM.h"
#import "C:\Code\TestVBA\TestVBA\bin\Release\TestVBA.tlb" raw_interfaces_only

using namespace TestVBA;
using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 // Initialize COM.
 long lResult = 0;
 HRESULT hr = CoInitialize(NULL);
 
 // Create the interface pointer.
 IVBAFuncPtr pIVBAFunc(__uuidof(VBAFunc));
 
 // Call the Add method.
 pIVBAFunc->Multiply(5, 10, &lResult);
 
 wprintf(L"The result is %d\n", lResult); 
 
 // Uninitialize COM.
    CoUninitialize();
 return 0;
}
或是
#import "C:\Code\TestVBA\TestVBA\bin\Release\TestVBA.tlb" raw_interfaces_only
using namespace TestVBA;
using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 // Initialize COM.
 long lResult = 0;
 HRESULT hr = CoInitialize(NULL);
 
 // Create the interface pointer.
 IVBAFuncPtr pVBAFuncPtr;
 HRESULT hRes = pVBAFuncPtr.CreateInstance(CLSID_VBAFunc);
 if (hRes == S_OK) 
 {
  // Call the Add method.
  pVBAFuncPtr->Multiply(10, 3, &lResult);
 } 
 
 wprintf(L"The result is %d\n", lResult); 
 
 // Uninitialize COM.
    CoUninitialize();
 return 0;
}
或是
#include "TestCOM.h"
#import "C:\Code\TestVBA\TestVBA\bin\Release\TestVBA.tlb" raw_interfaces_only

using namespace TestVBA;
using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 // Initialize COM.
 long lResult = 0;
 HRESULT hr = CoInitialize(NULL);
 
 //Get clsid by namespace and classname
 CLSID clsid;
 BSTR bstrDLL = _com_util::ConvertStringToBSTR("TestVBA.VBAFunc");
 HRESULT hResult = ::CLSIDFromProgID(bstrDLL, &clsid);
 if (!SUCCEEDED(hResult)) {
     return 1;
 }

 // Create the interface pointer.
 IVBAFuncPtr pIVBAFunc(clsid);

 // Call the Add method.
 pIVBAFunc->Multiply(5, 10, &lResult);
 
 wprintf(L"The result is %d\n", lResult); 
 
 // Uninitialize COM.
 CoUninitialize();

 return 0;
}
執行結果:

相關文章:
參考資料: