一樣使用前面的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; }執行結果:
相關文章:
- .NET C# 建立 COM元件 (1) --- 製作 Excel VBA 前期綁定元件
- .NET C# 建立 COM元件 (2) --- 製作 Excel VBA 後期綁定元件
- .NET C# 建立 COM元件 (3) --- 再談 Excel VBA 後期綁定元件
- How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005
- Calling Managed .NET C# COM Objects from Unmanaged C++ Code / COM Interop / C#
- call c# dll or class within c++ project
- COM Callable Wrapper
- C#的COM事件在C++和JAVA中触发和响应的实现
- Create a .NET COM and use it in Unmanaged C++
- [C#] C++からC#のDLLを呼ぶ方法
- 浅谈Excel开发:四 Excel 自定义函数