我写了一个ATL组件,加入一个接口Fun,一个函数long Add(long,long),编译成功。
另写一个控制台程序,用#import来引入这个dll,在main里面调用COM的函数。但是运行时,智能指针是空的。我想知道这个智能指针该如何初始化:#include "stdafx.h"
#include"Debug\\testatl.tlh"
#pragma comment(lib,"ole32")
int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(NULL);
    IFunPtr p;
    long L=p->Add(1,2);
    CoUninitialize();
    return 0;
}
在stdafx.h里面:#import "..\\Debug\\testatl.dll" no_namespace在testatl.tlh里面:_COM_SMARTPTR_TYPEDEF(IFun, __uuidof(IFun));
这个智能指针已经是定义了的。可是应该如何初始化它呢?

解决方案 »

  1.   

    还是需要CoCreateInstance()来创建你的接口.IFun
      

  2.   


    问题是,这个情况下我不知道CoCreateInstance()怎么创建,因为我没有IID_IFun:
        CoCreateInstance(Fun,NULL,NULL,IID_IFun,&pFun);
    编译不过。我的第四个参数应该如何指定?
      

  3.   

    你需要包含你的IFun组件的头文件和.c文件,这样就有IID_IFun了
      

  4.   

    可是,.tlh文件已经在末尾包含了.tli文件了:#include "d:\myproj\testprogid\zimport\debug\testatl.tli"我现在的main文件代码是:#include "stdafx.h"
    #include"Debug\\testatl.tlh"
    #pragma comment(lib,"ole32")
    int _tmain(int argc, _TCHAR* argv[])
    {
        CoInitialize(NULL);
        IFun *pFun;
        CoCreateInstance(Fun,NULL,NULL,IID_IFun,&pFun);
        IFunPtr p(pFun);
        long L=p->Add(1,2);
        CoUninitialize();
        return 0;
    }
      

  5.   

    自己再顶一下。这个IID到底应该怎么写? 自动生成的代码里面似乎没有iid啊
      

  6.   


    我改成了这样,现在没有编译错误了,但是CoCreateInstance就是失败,得不到IFun*,为什么?#include "stdafx.h"
    #include"Debug\\testatl.tlh"
    #pragma comment(lib,"ole32")
    int _tmain(int argc, _TCHAR* argv[])
    {
        CoInitialize(NULL);
        IFun *pFun;
        CoCreateInstance(__uuidof(Fun),NULL,NULL,__uuidof(IFun),(void**)&pFun);
        IFunPtr p(pFun);
        long L=p->Add(1,2);
        CoUninitialize();
        return 0;
    }
      

  7.   

    谢谢楼上的,现在改成这样就可以了!#include "stdafx.h"
    #include"Debug\\testatl.tlh"
    #pragma comment(lib,"ole32")
    int _tmain(int argc, _TCHAR* argv[])
    {
        CoInitialize(NULL);
        IFunPtr p;
        p.CreateInstance(__uuidof(Fun));
        long L=p->Add(1,2);
        p.Release();
        CoUninitialize();
        return 0;
    }