2014-05-03 60 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