C#的com組件編寫可以參照https://www.jianshu.com/p/be7f61ba7c86
下面主要講解如何調用
只能指針的方法對於非C++編寫的com組件經嘗試不適合
#include "atlcomcli.h"//和ATL聯合聲明纔可以,必須要使用這個包
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
CoInitialize(NULL);
CLSID clsid;
CLSIDFromProgID(OLESTR("ZhhCom.singleShoot"), &clsid); //"TestCom.MyCom"即爲Dll名+Com對
象名
{
ATL::CComPtr<Shoot> pMyCom;//智能指針的方法可以C++調用C++不適合調用C#
//使用 只能指針需要atlcomcli.h和ATL::ATL::CComPtr<com組件中的指針>
pMyCom.CoCreateInstance(clsid);
if (pMyCom == NULL)
{
return 111;
}
//pMyCom->showShoot();
}
//st.CreateInstance(CsharpComTest::CLSID_ComTest); //實例化一個類
return 0;
}
首先在Visual studio中新建項目,注意是win32應用程序
關鍵點到了,因爲涉及到跨語言的調用,因此會使用到代碼託管的功能,需要勾選 /clr框框裏的選項,公共語言運行時支持
然後導入dll文件,具體導入方法可以參考我的另一篇文章,https://blog.csdn.net/qwezhaohaihong/article/details/105707899,導入dll文件後代碼如下,
// ZhhLinkC++++Com.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#ifdef DEBUG
#using "ZhhCom.dll"
#else
#using "ZhhCom.dll"
#endif // DEBUG
#include<iostream>
#pragma managed //聲明代碼託管
using namespace ZhhCom;
//ZhhCom.Application
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nretcode = 0;
ZhhCom::singleShoot^ c = gcnew ZhhCom::singleShoot();//託管代碼創建C#類
c->showShoot();
system("pause");
return 0;
}
如果沒有在屬性中更改公共語言的支持則^c會報錯。ZhhCom是我組件的名稱,singleShoot是我組件中對shoot接口的實現類,gcnew是託管代碼創建C#類,showShoot()是singleShoot中的一個函數。
除了調用dll 還有 import的方式,但是import是import“xxx.tlb”不可以import dll,因爲dll是C#語言編寫的com組件,在c++無法直接支持。所以如果想使用C#組件建議使用using dll+設置屬性clr+gcnew的方法進行調用