从一个COM接口的Dll文件创建接口 - 模拟CoCreateInstance

大家知道,创建COM接口使用CoCreateInstance函数,这个函数是通过查注册表来载入dll的,我们如果不想注册COM模块,又不想用ATL那种方式,那就只能象我这样自己写一个类似CoCreateInstance的东西了。。。

#include <Windows.h>
#include <mmdeviceapi.h>

DECLSPEC_NOINLINE HRESULT WINAPI CoCreateInstanceFormDllFile(const IID& rclsid,const IID& riid,LPVOID* ppv,LPCWSTR lpszDllFile)
{
	register HRESULT hr = E_FAIL;
	HMODULE hComDll = GetModuleHandleW(lpszDllFile);
	if (!hComDll)
		hComDll = LoadLibraryExW(lpszDllFile,NULL,0);
	if (hComDll)
	{
		typedef HRESULT (WINAPI* _DllGetClassObject)(const IID&,const IID&,LPVOID*);
		_DllGetClassObject DllGetClassObject = (_DllGetClassObject)GetProcAddress(hComDll,"DllGetClassObject");
		if (DllGetClassObject)
		{
			IClassFactory* pClassFactory;
			hr = DllGetClassObject(rclsid,IID_PPV_ARGS(&pClassFactory));
			if (SUCCEEDED(hr))
			{
				hr = pClassFactory->CreateInstance(NULL,riid,ppv);
				pClassFactory->Release();
			}
		}else
			SetLastError(ERROR_BAD_DLL_ENTRYPOINT);
	}else
		SetLastError(ERROR_MOD_NOT_FOUND);
	return hr;
}

void main()
{
	CoInitialize(NULL);
	IMMDeviceEnumerator* pMMDeviceEnumerator;
	//CoCreateInstance(__uuidof(MMDeviceEnumerator),NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&pMMDeviceEnumerator));
	CoCreateInstanceFormDllFile(__uuidof(MMDeviceEnumerator),IID_PPV_ARGS(&pMMDeviceEnumerator),L"MMDevAPI.dll");
	pMMDeviceEnumerator->Release();
	ExitProcess(0);
}


你可能感兴趣的:(从一个COM接口的Dll文件创建接口 - 模拟CoCreateInstance)