COM的使用

//导出函数
void CTESTDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	//1.加载动态库
	HINSTANCE  m_hDll = LoadLibrary(_T("MyFirstCom.dll"));


	//2.根据函数名获取函数地址
	typedef   int(__stdcall * AddFun)(int numa, int numb);
	AddFun fun = (AddFun)GetProcAddress(m_hDll, MAKEINTRESOURCEA(1));


	//3.获取导出类对象指针,调用导出函数

	CString str;
	str.Format(_T("1 + 2 = %d"), fun(1, 2));
	MessageBox(str);

	//4.卸载dll
	FreeLibrary(m_hDll);
	
}
//COM中的类
#import "../MyFirstCom/Debug/MyFirstCom.tlb" named_guids, raw_interfaces_only, no_namespace
void CTESTDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code here
	//裸指针
	IMyCalculator* pMyCal;

	HRESULT	hr = CoCreateInstance(CLSID_MyCalculator, NULL, CLSCTX_INPROC_SERVER, IID_IMyCalculator, (void**)&pMyCal);
	if (SUCCEEDED(hr) && (pMyCal != NULL))
	{
		float ret;
		pMyCal->sub(12, 13, &ret);
		
		CString str;
		str.Format(_T("裸指针\n12 - 13 = %.2f"), ret);
		MessageBox(str);
	}
	pMyCal->Release();

	//智能指针
	CComPtr<IMyCalculator> spMyCal;
	hr = CoCreateInstance(CLSID_MyCalculator, NULL, CLSCTX_INPROC_SERVER, IID_IMyCalculator, (void**)&spMyCal);
	if (SUCCEEDED(hr) && (spMyCal != NULL))
	{
		float ret;
		spMyCal->add(12, 13, &ret);

		CString str;
		str.Format(_T("智能指针\n12 + 13 = %.2f"), ret);
		MessageBox(str);
	}
}

//封装IMyCalculator
class TestMyCalculator
{
public:
	TestMyCalculator()
	{
		HRESULT	hr = CoCreateInstance(CLSID_MyCalculator, NULL, CLSCTX_INPROC_SERVER, IID_IMyCalculator, (void**)&m_pMyCal);
		ASSERT(SUCCEEDED(hr) && (m_pMyCal != NULL));
		m_pMyCal->Begin();
		AfxMessageBox(_T("Begin"));
	}

	~TestMyCalculator()
	{
		m_pMyCal->End();
		AfxMessageBox(_T("End"));
	}

	void EndCalcu(){ AfxMessageBox(_T("End MyCalculator")); }
private:
	IMyCalculator* m_pMyCal;
};

void CTESTDlg::OnBnClickedButton3()
{
	// TODO: Add your control notification handler code here
	TestMyCalculator Test;
}

named_guids:告诉编译器以旧样式定义和初始化GUID变量,形式为LIBID_MyLib,CLSID_MyCoClass,IID_MyInterface和DIID_MyDispInterface。
raw_interfaces_only:使用函数时,禁止生成错误处理函数和属性(C ++)声明。
no_namespace:告诉编译器不生成命名空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值