2010-01-28 30 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