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 example:

 

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();

            pe.ExecuteFile("MethodTest.py");

 

            string myString1 = "test1";

            string myString2 = "test2";

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

 

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

 

 

The output is then:

 

test1test2

9

 

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, 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: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Brandon Furtwangler
Sent: Friday, January 06, 2006 1:08 PM
To: users@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 variables.

Ideas? Comments?

 

-Brandon Furtwangler

_______________________________________________
users mailing list
users@lists.ironpython.com
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com

Reply via email to