- 1. 概要
- 2. コマンドライン引数を取得する
- 3. MUTEX を使用した二重起動の防止
- 4. 現在日時を取得して文字列に変換
- 5. 引数の参照渡し
1. 概要
「C++/CLI」のメモなのだ・・・。
もう、ぐちを言うのも疲れてきたな。「VB」や 「C#」に比べて 「C++/CLI」に関しての記述のあるサイトは極端に少ないのです。
尚、例題は 「Visual Studio 2010」でのものです。
2. コマンドライン引数を取得する
コンソールプロジェクトがわかりやすいので
「新規作成」→「プロジェクト」→「Visual C++」→「CLR」→「CLR コンソール アプリケーション」

でプロジェクト名を入れて作成すると
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}
こういうプログラムが自動生成されます。まあ、C言語が分かっている人にはおおよその想像がつくってもんですが、わかりやすくアレンジすると
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
if (args->Length <= 0)
{
Console::WriteLine("コマンドライン引数がありません。");
}
else
{
for (int i=0; i<args->Length; i++)
{
String^ arg = args[i];
Console::WriteLine(arg);
}
}
return 0;
}
これで、引数を取得しているのが分かります。
3. MUTEX を使用した二重起動の防止
この稿、検証中。
Mutex^ mutex = gcnew Mutex(true, "システムで一意のミューテックス名");
bool capture = mutex->WaitOne(0, false);
if (capture == false)
{
return 0;
}
4. 現在日時を取得して文字列に変換
System::DateTime^ now = System::DateTime::Now;
Console::WriteLine(now->ToString("yyyyMMddHHmmss"));
5. 引数の参照渡し
プロトタイプ宣言は省略しておきますが(ていうかわかりますがね)、分かりやすく関数としておきます。
void sub(int& a, String^ b)
{
a = 1;
b = "2";
}
これを読んだ側では、「a」の値は 1 になっているが、「b」の値は "2" にならないのです。
C言語なら「*」なり、「&」なりの意味は、ほぼアセンブラレベルで想像がつくのですが、「C++/CLI」ではさっぱりわからない。
とりあえず、上位で見るときに値が変わっているようにするには
void sub(int& a, String^% b)
{
a = 1;
b = "2";
}
と、「^」の後ろに」「%」をつけるのです。
も~記号だらけで呪文のようですが、これで解決なのだ。
|
          |