0

特定のフォルダーの .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);
    }
}
4

1 に答える 1

0

marsha_as「特定のデータ オブジェクトに対してマーシャリングを実行し、マネージド データ型とネイティブ データ型の間で変換します」. ここに可能な型変換の表があります。

私はこのように使用します:

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;
}
于 2014-05-03T14:15:40.943 に答える