C言語からPythonの関数呼び出し4で
「実行ファイルと同じフォルダにあるpyモジュールも使いたいので,前回より少し手を加えた.」と書いていた部分であるが,なかなかみすぼらしいコードだったので少し考えて,代わりのコードを用意しようと思った.
変更のコードは以下に示すが,
本体は,実行ファイルのディレクトリを取得するGetModuleFileDirW()と
バックスラッシュをバックスラッシュ2つに変換するReplaceBS2BSBS()と
wstringをstringに変換するwstring2string().
#include <string>
#include <iostream>
#include <codecvt>
#include <windows.h>
std::wstring GetModuleFileDirW()
{
wchar_t path[MAX_PATH + 1];
::GetModuleFileNameW(NULL, path, sizeof(path));
wchar_t drive[MAX_PATH + 1], dir[MAX_PATH + 1], fname[MAX_PATH + 1], ext[MAX_PATH + 1];
_wsplitpath_s(path, drive, dir, fname, ext);
std::wstring wsDir = drive;
wsDir += dir;
return wsDir;
}
std::wstring ReplaceBS2BSBS(std::wstring wsDir)
{
{
std::wstring wstmp;
for (int i = 0; i < (int)wsDir.size(); ++i) {
wstmp += wsDir[i];
if (wsDir[i] == '\\') {
wstmp += TEXT("\\");
}
}
wsDir = wstmp;
}
return wsDir;
}
std::string wstring2string(std::wstring wsDir)
{
// wstring からstringへの変換
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
return cv.to_bytes(wsDir);
}
int main()
{
std::wstring wsDir = ::GetModuleFileDirW();
wsDir = ReplaceBS2BSBS(wsDir);
// wstring からstringへの変換
std::string sDir = ::wstring2string(wsDir);
std::cout << sDir.c_str() << std::endl;
return 0;
}
c_str()で前の例と同じchar[]に変換している.
