[IronPython] Calling a method with arguments from C#

Brandon Furtwangler furtwan1 at msu.edu
Fri Jan 6 20:35:02 CET 2006

Woot, I think I just wrote the exact method I was requesting.


I haven't tested it extensively but it seems to work so far.  Here is an


My python script looks like this (MethodTest.py):


def Add(s1, s2):

      return s1 + s2



And my C# is like this:


            PythonEngine pe = new PythonEngine();



            string myString1 = "test1";

            string myString2 = "test2";

            Console.WriteLine(pe.Evaluate("Add({0}, {1})", myString1,


            Console.WriteLine(pe.Evaluate("Add({0}, {1})", 4, 5)); 



The output is then:





As you can see I've added an overload to PythonEngine.Evalute that takes an
extra params array

public object Evaluate(string expr, params object[] args)


            Dictionary<object, object> locals = new Dictionary<object,


            //make sure we have less than 27 args because we are only using
1 letter variable names

            if (args.Length > 27)

                return new ArgumentException("You can only pass up to 27
arguments to this method");


            //for each argument, associate it with a one letter local
variable in python

            string[] argsVars = new string[args.Length];

            for (int i = 0; i < args.Length; i++)


                argsVars[i] = ((char)((int)'a' + i)).ToString(); //"a", "b",
"c", ...

                locals.Add(argsVars[i], args[i]);



            string exprFormat = string.Format(expr, argsVars);


            return Builtin.eval(_module, exprFormat,
Builtin.globals(_module), locals);


What do you think?  Is this something worth adding to the next release?  If
I'm not mistaken, there isn't an easy way to do this type of thing on your
own.please provide feedback because I'm new to IP and I might be missing
something simpler.


-Brandon Furtwangler


From: users-bounces at lists.ironpython.com
[mailto:users-bounces at lists.ironpython.com] On Behalf Of Brandon Furtwangler
Sent: Friday, January 06, 2006 1:08 PM
To: users at lists.ironpython.com
Subject: [IronPython] Calling a method with arguments from C#


Is it possible to call a python method from C# and pass C# variables as the
arguments?  For example py:

def Method3(person):

            return person.name


If so how do I call this from C# passing in some C# variable as person?


I'm thinking it should be something like:

pythonEngine.Evaluate("Method3({1})", myPerson);

In other words, I'd expect an overload of Evaluate to act as
Console.WriteLine and do whatever magic is required to link up the

Ideas? Comments?


-Brandon Furtwangler

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20060106/e9f8bae1/attachment.html>

More information about the Ironpython-users mailing list