我在导出 COM 对象的 ATL 服务时遇到问题。它作为本地服务运行,但是当作为 Windows 服务运行时,我无法连接。该服务正确启动并运行,但我的客户端(下面的代码)总是失败并出现错误“无法启动服务”。
所以我们在看同样的事情,我已经建立了一个最小的项目,可以在我的 PC 上重现这个问题。
File->New Project
Visual C++ -> ATL "ATL Project"
Name: "MyService"
在Application Settings下,选择"Service (EXE)"
转到“类视图”
右键单击“MyService”并添加 -> 类
选择:“ATL 简单对象”
短名称:“MyObject”
转到“解决方案视图”
右键单击“解决方案'MyService'”并添加->“新建项目”
这将是一个“Visual C++”->“Win32”“Win32 控制台应用程序”
名称:“MyClient”
检查“添加ATL 的通用头文件”框
在 client.cpp 中,使用以下代码:
#include "stdafx.h"
#import "../MyService/Debug/MyService.tlb"
#include <iostream>
using namespace MyServiceLib;
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize( NULL );
try
{
IMyObjectPtr spQueue( __uuidof( MyObject ) );
}
catch( const _com_error& Err )
{
std::wcout << L"Error: " << Err.ErrorMessage() << std::endl;
}
catch( ... )
{
std::wcout << L"Unexpected Error" << std::endl;
}
::CoUninitialize();
std::wcout << L"Finished" << std::endl;
return 0;
}
打开“项目依赖”
项目“MyClient”依赖于“MyService”
构建解决方案。
在命令提示符下,运行以下命令:
MyService /Service
net start MyService
client