Can IronPython access members of a C# class instance?

Started by
-1 comments, last by Daichi 12 years, 1 month ago
So, I can get an instance of a C# class just fine to IronPython, but I can't seem to do much of anything with it's members or functions. Is there anyway to get around this problem? The IronPython documentation and my searches hasn't led me very far on figuring this out for the past several hours.

Here is a simplified example of what I'm trying to do:
class Unit
{
public int HP { get; set; }
public int Attack { get; set; }

public Unit(int HP, int Attack)
{
this.HP = HP;
this.Attack = Attack;
}
public void PointlessFunction() { }
public override string ToString()
{
return "HP: " + HP.ToString() + " Attack: " + Attack.ToString();
}
}

class Program
{
static void Main(string[] args)
{
ScriptEngine Engine = Python.CreateEngine();
ScriptScope Scope = Engine.CreateScope();

Scope.SetVariable("Unit", DynamicHelpers.GetPythonTypeFromType(typeof(Unit)));

// declare instance of Unit
Engine.Execute("u = Unit(10,5)", Scope);

// display Unit instance
Engine.Execute("print u", Scope);
//HP: 10 Attack: 5

// Try to change something
Engine.Execute("u.HP = 20", Scope);
//Unhandled Exception: System.MissingMemberException: 'Unit' object has no attribute 'HP'

// Try to run a function
Engine.Execute("u.PointlessFunction()", Scope);
//Unhandled Exception: System.MissingMemberException: 'Unit' object has no attribute 'PointlessFunction'
}
}

This topic is closed to new replies.

Advertisement