IronPythonとC#で変数をやり取りする時に、C#ではどう見えるのか、どう変換されるのか?
これは、IronPythonとC#の連携を行う際には重要な質問です。IronPythonと違い、C#は変数を定義する際に型を定義する必要があるからです。
C#にはGetType()
関数があるのでこれを使って確認してみます。
本記事はこちらの記事を、「Visual Studio 2022」 + 「IronPython 3.4」の内容で修正しています。 ちなみに、.NET Framework 4.8です。IronPython 3.4.0-beta1でintとlongが統合されたようです。Int32を超える数になると、BigIntegerになるので注意が必要です。
サンプルによる確認
こちらにサンプルプログラムを作成しました。
以下のように、GetType()
を利用したGetTypeCS()
とGetTypeCs_IList()
を作成しました。
IronPythonのリストは、C#の関数の引数をIList型にしておけば渡すことが可能です。
public static string GetTypeCs_IList(IList<object> obj)
以下、プログラムです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyUtil
{
public class MyFunction
{
public static string GetTypeCs(object obj)
{
try
{
return obj.GetType().ToString();
}
catch (Exception ex)
{
string msg = "Exception " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message;
throw new ApplicationException(msg);
}
}
public static string GetTypeCs_IList(IList<object> obj)
{
try
{
return obj[0].GetType().ToString();
}
catch (Exception ex)
{
string msg = "Exception " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message;
throw new ApplicationException(msg);
}
}
}
}
GetTypeCs.sln
を開きReleaseビルドしてから、Release
フォルダをVisual Studio Codeで開き(手順はこちらを参考にしてください)、example_GetTypeCs.py
を実行してください。
IronPython 3.4-beta1以降では、int(Int32)とlong(BigInteger)が統合されており、C#のコード上では注意が必要です。(IronPython上でも「1L」のような表記はできなくなりました)