2009年9月3日木曜日

TValue型を試してみる

Rttiユニットで新たに定義されたTValue型は、汎用に使えるデータ型に
なっていて、Delphiで使う基本的な型は、Implicit演算子が定義されており
代入可能になっている。

で、実験してみた。以下ソースコード



program Project1;
{$APPTYPE CONSOLE}

uses
SysUtils,
rtti,
typinfo;

var
tv: TValue;
obj: TObject;
intary: Array of TValue;

begin
try
{ TODO -oUser -cConsole Main : ここにコードを記述してください }
// 先ずは何も入れない場合
if tv.IsEmpty then
begin
writeln('TValueはからです');
end;

tv := 100;
writeln('TValueは' + tv.TypeInfo.Name + 'です。');

tv := 100.0;
writeln('TValueは' + tv.TypeInfo.Name + 'です。');

tv := 'saka';

writeln('TValueは' + tv.TypeInfo.Name + 'です。');

obj := TObject.Create;
tv := obj;
writeln('TValueは' + tv.TypeInfo.Name + 'です。');

tv := obj.ClassType;
writeln('TValueは' + tv.TypeInfo.Name + 'です。');

obj.Free;

end.



で実行した様子が下図。

2009年8月29日土曜日

Rttiを試してみるその4

以前のポストで、可視性がPrivateのメソッドは、読めないということを
記述しましたが、実際には、

自分で定義したメソッドであれば

コンパイラ指定{$RTTI EXPLICIT METHODS}で
TRttiContextのGetMehtodで列挙する可視性を制御することが可能のようです。

{$RTTI EXPLICIT METHODS([vcPublished,vcPublic,vcProtected,vcPrivate])}

とすれば、すべての可視性の列挙が可能です。(正し、継承元のメソッドには
可視性の制御は及ばない見たいです。)

また、

{$RTTI EXPLICIT METHODS([vcPrivate])}

とすれば、Private可視性のメソッドの列挙が可能です。

以下、検証ように使ったソースです。


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CheckLst;

type
TForm1 = class(TForm)
Button1: TButton;
CheckListBox1: TCheckListBox;
procedure Button1Click(Sender: TObject);
private
{ Private 宣言 }
public
{ Public 宣言 }
end;

var
Form1: TForm1;

implementation

uses Rtti,Typinfo,Unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
ctx : TRttiContext;
rtmary : TArray;
rtm : TRttiMethod;
obj : TObject;
Args : Array of TValue;
rtp : TRttiType;
idx : Integer;
begin

ctx := TRttiContext.Create;

//自分で定義したメソッドのみを取得するには、
//GetDeclaredMethodsを使います。
rtmary := ctx.GetType(Unit2.TSakaTest).GetDeclaredMethods;
//rtmary := ctx.GetType(Unit2.TSakaTest).GetMethods();

CheckListBox1.Clear;

if rtmary <> nil then
begin
for rtm in rtmary do
begin
idx := CheckListBox1.Items.Add(rtm.Name);
if rtm.Visibility = TMemberVisibility.mvPrivate then
begin
CheckListBox1.Checked[idx] := true;
end;

end;

end;

end;

end.






unit Unit2;
interface

uses classes;

// {$RTTI EXPLICIT METHODS([vcPublished,vcPublic,vcPrivate])}
{$RTTI EXPLICIT METHODS([vcPrivate])}
Type TSakaTest = Class(TObject)
private
function SayPrivateMessage : String;
public
function SayPublicMessage : String;
End;

implementation

{ TSakaTest }

function TSakaTest.SayPrivateMessage: String;
begin
Result := 'This is a Private Method';
end;

function TSakaTest.SayPublicMessage: String;
begin
Result := 'This is a Public Method';
end;

end.

Rttiを試してみるその3

文字列で指定したクラスのインスタンスを作成する例を作ってみました。
(Button3Click)
試行錯誤のうえで作成したソースなので、とりあえず動きましたが
正しいソースかどうかは、分かりません。もっと良い方法が
あれば教えて下さい。

この手の処理はActivatorクラスのある.Netのほうが簡単だと
思います。


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls,Unit2;

type
TForm2 = class(TForm)
Button3: TButton;
LabeledEdit1: TLabeledEdit;
ListBox1: TListBox;
Button1: TButton;
Label1: TLabel;
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private 宣言 }
protected
public
{ Public 宣言 }

end;

var
Form1: TForm2;
implementation
uses
Rtti,TypInfo;

{$R *.dfm}


procedure TForm2.Button1Click(Sender: TObject);
var
LContext: TRttiContext;
LType: TRttiType;
LTypes:TArray;

begin

LoadPackage('SakaPack.bpl');

{ Obtain the RTTI context }
LContext := TRttiContext.Create;

{ Obtain the second package (rtl140) }
LTypes := LContext.GetTypes();

{ Enumerate all types in the rtl140 package }

//for LPackage in LPackages do
//begin
for LType in LTypes do
begin
ListBox1.Items.Add(LType.QualifiedName);
end;
//end;
ListBox1.Items.SaveToFile('P.Txt');

end;

procedure TForm2.Button3Click(Sender: TObject);
var
ctx : TRttiContext;
rtm : TRttiMethod;
rst : TValue;
SakaInf : ISakaTest;
rtt : TRttiType;
Args : Array of TValue;


begin

//とりあえず別パッケージで動的ロード化とする
LoadPackage('SakaPack.bpl');

ctx := TRttiContext.Create;

//文字列で型情報を探す場合は、FindTypeを使う
//完全一致なのでユニット名を含めて指定
rtt := ctx.FindType('Unit2.' + LabeledEdit1.Text);

//コンストラクタはとりあえずCreateであることが前提
rtm := rtt.GetMethod('Create');

if rtm <> nil then
begin
if rtm.IsConstructor then
begin
//1. クラスの場合は、TRttiInstanceTypeで戻ってくるのでキャスト
//2. MetaaclassTypeプロパティで実際のクラスがとれるみたい。
rst := rtm.Invoke(TRttiInstanceType(rtt).MetaclassType,Args);
if rst.IsObject Then
begin
SakaInf := TSakaTest(rst.AsObject) As ISakaTest;
Label1.Caption := SakaInf.SayMessage();
end;
//Label1.Caption := obj.ClassName;
end;
end;


end;

end.


でUnit2で使ったソースがこちら



unit Unit2;

interface
uses classes;

{$RTTI EXPLICIT METHODS([vcPublic])}
Type ISakaTest = interface(IInterface)
['{FAAA20A5-E078-4E22-96C2-139E7E57CBFB}']
function SayMessage : String;
end;

{$RTTI EXPLICIT METHODS([vcPublished,vcPublic])}
Type TSakaTest = Class(TInterfacedPersistent, ISakaTest)
function SayMessage : String; virtual;
End;

{$RTTI EXPLICIT METHODS([vcPublished,vcPublic])}
Type TSakaTest1 = Class(TSakaTest)
Public
function SayMessage : String; override;
End;

{$RTTI EXPLICIT METHODS([vcPublished,vcPublic])}
Type TSakaTest2 = Class(TSakaTest)
Public
function SayMessage : String; override;
End;

var
SakaTest : ISakaTest;

implementation

//uses
//Classes;



{ TSakaTest1 }

function TSakaTest1.SayMessage: String;
begin
Result := 'Hello Delphi First';
end;

{ TSakaTest2 }

function TSakaTest2.SayMessage: String;
begin
Result := 'Hello Delphi Second';
end;

{ TSakaTset }

function TSakaTest.SayMessage: String;
begin
Result := '';
end;

initialization
RegisterClass(TSakaTest);
RegisterClass(TSakaTest1);
RegisterClass(TSakaTest2);

end.

Jedi VCL Versionアップ

Delphi 2010の対応です。

ユニットを使うダイアログ


Unitの追加先を選択できるようになってたんだ。
気づかなかった。

Rttiを試して見るその2

前回のポストに引き続いて、メソッドの動的呼び出し。

整数の足し算を行う例です。以下ソース


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Button3: TButton;
LabeledEdita: TLabeledEdit;
Label1: TLabel;
LabeledEditb: TLabeledEdit;
Label2: TLabel;
LabelResult: TLabel;
procedure Button3Click(Sender: TObject);
private
{ Private 宣言 }
protected
public
{ Public 宣言 }
function Sakasum(a,b : Integer) : Integer;

end;

var
Form1: TForm1;

implementation
uses
Rtti,TypInfo;

{$R *.dfm}


procedure TForm1.Button3Click(Sender: TObject);
var
ctx : TRttiContext;
rtm : TRttiMethod;
Args : Array of Rtti.TValue;
rst : TValue;
begin
//
ctx := TRttiContext.Create;
rtm := ctx.GetType(Self.ClassType).GetMethod('SakaSum');

if rtm <> nil then
begin
SetLength(Args,2);
//TValueは、演算子Implicitが定義されているので基本的な型は
//変換による代入が可能
Args[0] := StrToInt(LabeledEdita.Text);
Args[1] := StrToInt(LabeledEditb.Text);
rst := rtm.Invoke(Self,Args);
//結果はAsXXXXX関数を使って取り出せる。
Self.LabelResult.Caption := IntToStr(rst.AsInteger);
end;
end;


function TForm1.Sakasum(a, b: Integer): Integer;
begin
Result := a + b;
end;

end.


TValueの使い方が分からなくて結構悩みました。

で、ソースをみたら基本的な型については、
Implicit演算子のオーバーロードが
定義されているのね。

このへんはHelpに書いといて欲しかったです。
(C++ のHELPには書いてあります。)

(英語版のDoc Wikiがメンテナンス中だったので
日本語版でのみ書いていないのかはちょっと不明です。)

また、こちらにDelphi Prismで上記と同様な処理を
記述しました
。

2009年8月28日金曜日

Rttiを試して見る

動的にメソッドを読み出す簡単なプログラムを作ってみました。
プログラムそのものには意味はありません。

プレビュー会に説明があったようにprivateなメソッドは読めませんでした。
メソッドの可視属性を示す型があったので読めてもよいと思ったのですが・・・

また、GetDeclaredMethodsをつかうと自分が宣言したメソッドのみ
リストできます。

以下ソースです。


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
LabeledEdit1: TLabeledEdit;
Button2: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private 宣言 }
//procedure SakaTest2;
protected
//procedure SakaTest1;
procedure SakaTest2;
public
{ Public 宣言 }
procedure SakaTest2;
procedure SakaTest1;
end;

var
Form1: TForm1;

implementation
uses
Rtti,TypInfo;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
ctx : TRttiContext;
rtm : Rtti.TRttiMethod;
obj : TObject;
Args : Array of TValue;
begin
//
ctx := TRttiContext.Create;


//rtm := ctx.GetType(obj).GetMethod(LabeledEdit1.Text);

rtm := ctx.GetType(Self.ClassType).GetMethod(LabeledEdit1.Text);

if rtm <> nil then
begin
//obj := Self;
rtm.Invoke(Self,Args);
end;

end;

procedure TForm1.Button2Click(Sender: TObject);
var
ctx : TRttiContext;
rtmary : TArray;
rtm : TRttiMethod;
obj : TObject;
Args : Array of TValue;
rtp : TRttiType;
begin

ctx := TRttiContext.Create;

//rtm := ctx.GetType(obj).GetMethod(LabeledEdit1.Text);
//ctx.FindType()
//rtp := ctx.GetType(Self.ClassType);
//rtp.IsPublicType := false;

rtmary := ctx.GetType(Self.ClassType).GetDeclaredMethods;

ListBox1.Clear;

if rtmary <> nil then
begin
for rtm in rtmary do
begin
ListBox1.Items.Add(rtm.Name);
if rtm.Name = LabeledEdit1.Text then
begin
rtm.Invoke(Self,Args);
end;

end;

end;

end;

procedure TForm1.SakaTest1;
begin
Application.MessageBox('Hello Delphi','First Text');
end;

procedure TForm1.SakaTest2;
begin
Application.MessageBox('Hello Delphi','Second Text');
end;

end.


引数つきのメソッドコールはまた次回