发表于:2007-10-02 14:56:00
楼主
//这是一个简单的OPC Client 入门程序
//main.cpp
//************************************************************************************************
//浏览本地OPC服务器
//************************************************************************************************
#define _WIN32_DCOM // Needed in order to call CoInitializeEx()
#include <iostream>
#include <objbase.h>
#include <comdef.h>
#import "C:\WINNT\system32\OpcEnum.exe" no_namespace //根据OpcEnum.exe更改
#include "opcda.h"
#include "opcenum_i.c"
//--------------------------------------------------------------------------------------------------------------
//版本号----可以从规范中查到
static const CLSID CATID_OPCDAServer10 =
{ 0x63d5f430, 0xcfe4, 0x11d1, { 0xb2, 0xc8, 0x0, 0x60, 0x8, 0x3b, 0xa1, 0xfb } };
// {63D5F430-CFE4-11d1-B2C8-0060083BA1FB}
static const CLSID CATID_OPCDAServer20 =
{ 0x63d5f432, 0xcfe4, 0x11d1, { 0xb2, 0xc8, 0x0, 0x60, 0x8, 0x3b, 0xa1, 0xfb } };
// {63D5F432-CFE4-11d1-B2C8-0060083BA1FB}
//[uuid(CC603642-66D7-48f1-B69A-B625E73652D7)] interface CATID_OPCDAServer30
//--------------------------------------------------------------------------------------------------------------
void OPCServerList();
int main(int argc, char* argv[])
{
HRESULT hr;
int n_return = 0;
try
{
// Initialize COM
if(
FAILED( hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) )
)
_com_issue_error(hr);
}
catch(_com_error e)
{
std::cout << "ERROR(" << e.Error() << "): ";
if( e.Description().length() > 0)
std::cout << (TCHAR*)e.Description() << std::endl;
else
std::cout << e.ErrorMessage() << std::endl;
n_return = 1;
}
OPCServerList();
// Uninitialize COM
CoUninitialize();
return 0;
}
//使用CoCreateInstance
void OPCServerList()
{
CLSID clsid;
clsid = CLSID_OpcServerList; //在opcenum_i.c中定义
IOPCServerList *gpOPC = NULL;
DWORD clsctx;
clsctx = CLSCTX_LOCAL_SERVER; //本地服务
IID IIDOPCServerList=IID_IOPCServerList; //在opcenum_i.c中定义
// 创建OPC服务器的浏览器对象-----
HRESULT hr = CoCreateInstance(clsid, NULL, clsctx,IIDOPCServerList ,(void**)&gpOPC);
// 查询OPC DA 2.0 组件目录接口指针
CLSID catid;
catid=CATID_OPCDAServer20; //= CATID_OPCDAServer20; //OPC数据访问服务器2.0组件目录
IOPCEnumGUID *pEnumGUID;
hr = gpOPC->EnumClassesOfCategories( 1, &catid, 1, &catid, (IEnumGUID**)&pEnumGUID);
if(S_OK!=hr)
return;
//获得支持OPC DA2.0数据服务器的CLSID
unsigned long c;
while (S_OK == pEnumGUID->Next(1, &clsid, &c))
{
LPOLESTR pszProgID;
LPOLESTR pszUserType;
hr =&