从控制台应用程序调用 COM DLL






3.09/5 (8投票s)
本文解释了如何从控制台应用程序调用 COM DLL
引言
本文档展示了如何在 C 语言的控制台应用程序中调用 VC++ DLL。
入门
- 创建一个新的 ATL 项目用于 DLL,点击完成。
- 使用 ATL 对象向导添加一个简单的对象,短名称为 mydll,接受默认设置。
- 使用类视图向新的接口添加方法,方法名为
multiply
,参数为 '[in] int ifirst,[in] int isecond,[out] int* result
'。
你的方法应该如下所示
STDMETHODIMP Cmydll::multiply(int ifirst, int isecond, int *result) { // TODO: Add your implementation code here *result = ifirst * isecond; return S_OK; }构建并注册 DLL。现在创建一个名为 'CallCDLL' 的 Win32 控制台应用程序。
包含
#include <stdio.h> #include <objbase.h> #include "dll4C.h" //contains prototype of method #include "dll4C_i.c" //contains the Class ID ( CLSID ) //and Interface ID ( IID )你的
Main()
函数应该如下所示int main(void) { IClassFactory* pclsf; IUnknown* pUnk; Imydll* pmydll; int x,y; int result; //Initialize the OLE libraries CoInitialize(NULL); //get the IClassFactory Interface pointer HRESULT hr = CoGetClassObject(CLSID_mydll,CLSCTX_INPROC,NULL, IID_IClassFactory,(void**)&pclsf); if(!SUCCEEDED(hr)) { printf("CoGetClassObject failed with error %x\n",hr); return 1; } //Use IClassFactory's CreateInstance to create the COM object //and get the IUnknown interface pointer hr = pclsf->CreateInstance(NULL,IID_IUnknown,(void**)&pUnk); if(!SUCCEEDED(hr)) { printf("ClassFactory CreateInstance failed with error %x\n",hr); return 1; } //Query the IUnknown to get to the Imydll interface hr = pUnk->QueryInterface(IID_Imydll,(void**)&pmydll); if(!SUCCEEDED(hr)) { printf("QueryInterface failed with error %x\n",hr); return 1; } //Use Imydll interface for multiplications printf("Input two numbers to multiply:\n"); scanf("%d\n%d",&x,&y); pmydll->multiply(x,y,&result);//call the method using //the interface pointer printf("The product of the two numbers %d and %d = %d\n", x,y,result);//print the result //Release the interface pointers pmydll->Release(); pclsf->Release(); return 0; }
结论
就这样。如有任何疑问或建议,请与我联系。