2010-01-28 28 views
1

尝试在C++中包装this简短示例。 (自从我这样做以来已经有一段时间了)。如何在C++中打包CFtpFileFind示例?

int main(int argc, char* argv[]) 
{  
    //Objects 
    CFtpConnection* pConnect = NULL; //A pointer to a CFtpConnection object 
    ftpClient UploadExe; //ftpClient object 


    pConnect = UploadExe.Connect();  
    UploadExe.GetFiles(pConnect); 

system("PAUSE"); 
    return 0; 
} 

.H -

class ftpClient 
{ 
    public:  

    ftpClient();   
    CFtpConnection* Connect(); 
    void GetFiles(CFtpConnection* pConnect);  

}; 

的.cpp -

//constructor 
ftpClient::ftpClient() 
{ 

} 

CFtpConnection* ftpClient::Connect() 
{ 
    // create a session object to initialize WININET library 
    // Default parameters mean the access method in the registry 
    // (that is, set by the "Internet" icon in the Control Panel) 
    // will be used. 

    CInternetSession sess(_T("FTP")); 

    CFtpConnection* pConnect = NULL; 

    try 
    { 
     // Request a connection to ftp.microsoft.com. Default 
     // parameters mean that we'll try with username = ANONYMOUS 
     // and password set to the machine name @ domain name 
     pConnect = sess.GetFtpConnection("localhost", "sysadmin", "ftp", 21, FALSE); 

    } 
    catch (CInternetException* pEx) 
    { 
     TCHAR sz[1024]; 
     pEx->GetErrorMessage(sz, 1024); 
     printf("ERROR! %s\n", sz); 
     pEx->Delete(); 
    } 

    // if the connection is open, close it MOVE INTO CLOSE FUNCTION 
    // if (pConnect != NULL) 
    // { 
    //  pConnect->Close(); 
    //  delete pConnect; 
    // } 


    return pConnect; 

} 

void ftpClient::GetFiles(CFtpConnection* pConnect) 
{ 
     // use a file find object to enumerate files 
     CFtpFileFind finder(pConnect); 


if (pConnect != NULL) 
{ 
    printf("ftpClient::GetFiles - pConnect NOT NULL"); 
} 


    // start looping 
     BOOL bWorking = finder.FindFile("*"); //<---ASSERT ERROR 

     // while (bWorking) 
     // { 
    //  bWorking = finder.FindNextFile(); 
    //  printf("%s\n", (LPCTSTR) finder.GetFileURL()); 
    // } 


} 

因此,基本上分离的连接和文件操作为2层的功能。 findFile()函数抛出断言。 (步入findFile(),它特别位于inet.cpp中的第一个ASSERT_VALID(m_pConnection)。)

我是如何通过环绕CFtpConnection * pConnect外观的?

EDIT - 在GetFiles()函数中看起来像CObject vfptr被覆盖(0X00000000)。

任何帮助表示赞赏。谢谢。

回答

1

解答:

该会话对象必须在连接功能进行分配,以声明为类的成员函数的指针
。在函数中创建对象时,当函数退出时,对象/会话将被终止,被抛出堆栈。发生这种情况时,我们不能在其他函数中使用pConnect指针。

WinInet对象具有层次结构,会话位于顶层。如果会话没有了,其他的都不能使用。因此,我们必须使用new来分配内存中的对象,以便在此函数退出后维持它。

1

我不认为让ftpClient类从Connect中返回CFTPConnection对象没有任何实际价值(除非我错过了你打算的东西?) - 它应该只是将它作为一个成员变量,并且GetFiles可以直接使用该成员(同样,您可以将CInternetSession添加为类的成员,并避免上述问题超出范围时)。

以这种方式,ftpClient管理CFTPConnection的生存期并可以在其析构函数中销毁它。

+0

将CFTPConnection对象更改为成员变量。 – 2010-01-29 17:11:30