C#とIronPython間のオブジェクトI/F

C#IronPythonの間でオブジェクトの受け渡しは簡単に行う事ができる。

C#IronPython(C#でオブジェクトを定義)

//C#コード
string str ;
PythonEngine python_engine =  new PythonEngine();
python_engine.Globals.Add("sss", str);	// C#のオブジェクトを公開
--
#IronPythonコード
cells = p_cell.split( sss )	#参照している
sss = 'ret'	#設定している。

IronPythonC#(IronPythonでオブジェクトを定義)

#IronPythonコード
ret_val = 'return value'	# ret_valを定義
--
//C#コード
string str1 = python_engine.EvaluateAs<string>("ret_val");	# IronPythonのオブジェクトを参照


上記はシンプルに文字列の場合で、その他の場合は以下。

タプル

IronPythonのタプルはC#の[]に対応している。

#IronPythonコード
ret_val = (5,7)
--
// C#コード
int[] a = PE.EvaluateAs<int[]>("ret_val");

配列

配列の場合はそのままではできないので、ArrayList経由で渡す。

#IronPythonコード
from System.Collections import *

a = [45,56]
ret_val = ArrayList( a )
--
// C#コード
ArrayList v = PE.EvaluateAs<ArrayList>("ret_val");

辞書

辞書の場合はHashtable経由。

#IronPythonコード
from System.Collections import *

ht = {'str1' : 'sss1' , 'str2' : 'sss2' }
ret_val = Hashtable( ht )
--
// C#コード
Hashtable ht = PE.EvaluateAs<Hashtable>("ret_val");

クラスのインスタンス

C#側で宣言したクラスのオブジェクトは渡せるけど、逆はできない気がする。

// C#コード
public class Hoge
{
	public int a ;
	public void func() { } ;
}

Hoge h = new Hoge() ;

PythonEngine PE =  new PythonEngine();
PE.Globals.Add("h_inst", h );

PE.ExecuteFile("py_script.py");

Hoge h_ret = PE.EvaluateAs<Hoge>( "ret_val" ) ;

--

#IronPythonコード
h_inst.a = 5	# メンバアクセス可能
h_inst.func()	# メソッド呼び出し可


ret_val = h_inst	# 返すのも可

ある程度はサクサク受け渡しできるが、C#クラスオブジェクトの配列を返そうとかすると、IronPython側でC#のオブジェクトを作れなくてはまる。
とりあえずの解決策としては、Hoge HogeFactory() { return new Hoge() ;}みたいな関数をC#で用意して、IronPython側から呼ぶぐらいか。
IronPython側からC#のクラス定義を見る方法がなんかありそうなんだけどな。