//导出函数
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:告诉编译器不生成命名空间。