System :: String ^到TCHAR *

时间:2014-05-03 13:59:17

标签: c++-cli clr tchar

我有一个类,它收集给定文件夹的.txt文件的所有路径,并将它们存储到一个向量中。我使用的大多数函数都需要使用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;
}

这是我需要将System :: String ^转换为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 个答案:

答案 0 :(得分:0)

marsha_as&#34;对特定数据对象执行封送处理,以在托管数据类型和本机数据类型之间进行转换&#34;。 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;
}