2014-05-03 112 views
0

我有一個類收集給定文件夾的.txt文件的所有路徑,並將它們存儲到一個向量中。我使用的大多數函數都需要使用TCHAR *來獲取/設置當前目錄等等。System :: String^to TCHAR *

類看起來是這樣的:

typedef std::basic_string<TCHAR> tstring; 
class folderManager 
{ 
private: 
    TCHAR searchTemplate[MAX_PATH]; 
    TCHAR directory[MAX_PATH];   

    WIN32_FIND_DATA ffd; 
    HANDLE hFind;   

    vector<tstring> folderCatalog; 
    vector<tstring> fileNames;  

    bool succeeded; 

public: 
    // get/set methods and so on... 
}; 
// Changed TCHAR* dir to tstring dir 
void folderManager::setDirectory(tstring dir) 
{ 
    HANDLE hFind = NULL; 
    succeeded = false; 

    folderCatalog.clear(); 
    fileNames.clear(); 
    // Added .c_str() 
    SetCurrentDirectory(dir.c_str()); 
    GetCurrentDirectoryW(MAX_PATH, directory); 

    TCHAR fullName[MAX_PATH]; 

    StringCchCat(directory, MAX_PATH, L"\\"); 

    StringCchCopy(searchTemplate, MAX_PATH, directory); 
    StringCchCat(searchTemplate, MAX_PATH, L"*.txt"); 

    hFind = FindFirstFile(searchTemplate, &ffd);  

    if (GetLastError() == ERROR_FILE_NOT_FOUND) 
    { 
     FindClose(hFind); 
     return; 
    } 
    do 
    { 
     StringCchCopy(fullName, MAX_PATH, directory); 
     StringCchCat(fullName, MAX_PATH, ffd.cFileName); 

     folderCatalog.push_back(fullName); 
     fileNames.push_back(ffd.cFileName); 
    } 
    while (FindNextFile(hFind, &ffd) != 0); 

    FindClose(hFind); 
    succeeded = true; 
} 

這是我需要做的轉換系統::字符串^到TCHAR *

private: System::Void dienuFolderisToolStripMenuItem_Click(System::Object^ 
    sender, System::EventArgs^ e) 
{ 
    FolderBrowserDialog^ dialog; 
    dialog = gcnew System::Windows::Forms::FolderBrowserDialog; 

    System::Windows::Forms::DialogResult result = dialog->ShowDialog(); 
    if (result == System::Windows::Forms::DialogResult::OK) 
    { 
        // Conversion is now working.   
     tstring path = marshal_as<tstring>(dialog->SelectedPath); 
     folder->setDirectory(path); 
    } 
} 
+1

只要在任何地方使用wstring。所有可以運行現代.NET版本的Windows都有unicode API。 –

+0

本說的是,幾乎可以肯定的是,[你不需要TCHAR](http://stackoverflow.com/q/4205809/2226988)。 –

回答

0

marsha_as「在一個特定的執行封送處理數據對象在託管數據類型和原生數據類型之間進行轉換「。 Here有可能的類型轉換表。

我使用這種方式:

marshal_as<std::wstring>(value) 

TCHAR可以是char或wchar_t的,他們都出現在marshal_as專業化的,我想你需要點TCHAR *爲模板參數:

TCHAR* result = marshal_as<TCHAR*>(value) 

其實MSDN說你必須這樣使用它:

#include <msclr\marshal.h> 

using namespace System; 
using namespace msclr::interop; 

int main(array<System::String ^> ^args) 
{ 
    System::String^ managedString = gcnew System::String("Hello World!!!"); 

    marshal_context^context = gcnew marshal_context(); 
    const wchar_t* nativeString = context->marshal_as<const wchar_t*>(managedString); 
    //use nativeString 
    delete context; 

    return 0; 
} 
+0

我試過你提到的第一種方法,但是我遇到了將wstring轉換爲TCHAR *的問題。第二個選項給我一個很長的錯誤(這個轉換不被庫支持......) – Edd

+0

std :: wstring和TCHAR *都是本地類型,在這種情況下你不需要使用marshal_as。你的問題是如何將String ^轉換爲TCHAR *? – Serhiy

+0

我得到它的工作,將編輯解決方案的主要帖子,謝謝! – Edd