[Python.NET] C# dynamic object support / Easy calling from C#

Tribble, Brett btribble at ea.com
Fri Jul 5 18:41:55 CEST 2013


Star Trek jokes, yeah, heard those...

From: PythonDotNet [mailto:pythondotnet-bounces+btribble=ea.com at python.org] On Behalf Of Mark Tigges
Sent: Friday, July 05, 2013 7:49 AM
To: Patrick Stewart
Cc: pythondotnet at python.org
Subject: Re: [Python.NET] C# dynamic object support / Easy calling from C#

Nice work captain! (sorry, couldn't resist.)

On Tue, Jul 2, 2013 at 2:35 AM, Patrick Stewart <patstew at gmail.com<mailto:patstew at gmail.com>> wrote:
Hi,
Just thought I'd send a heads up to say I've made some modifications to python.net<http://python.net> to make it much more convenient to call python code from C#, which can be found here: http://github.com/patstew/pythonnet
I've inherited PyObject from DynamicObject, wired up the appropriate bits and added a few convenience functions, so now you can write C# code like this:

static void Main(string[] args)
{
using (Py.GIL()) {
dynamic np = Py.Import("numpy");
dynamic sin = np.sin;
Console.WriteLine(np.cos(np.pi*2));
 Console.WriteLine(sin(5));
Console.WriteLine(np.cos(5) + sin(5));
dynamic a = np.array(new List<float> { 1, 2, 3 };
dynamic b = np.array(new List<float> { 6, 5, 4 }, Py.kw("dtype", np.int32));                     Console.WriteLine(a.dtype);
Console.WriteLine(b.dtype);
Console.WriteLine(a * b);
Console.ReadKey();
}
}

which outputs:

1.0
-0.958924274663
-0.6752620892
float64
int32
[  6.  10.  12.]

as you might expect. You can call, access members and perform mathematical operations all as normal. Managed arguments are automatically converted to python types when used with a python function, and mathematical operations like multiplying numpy arrays happen entirely within python. You can specify keyword arguments using Py.kw("key1", value1, "key2", value2, ....) as an extra argument to the function. One slight annoyance is that np.pi*2 works while 2*np.pi doesn't, due to limitations of DynamicObject.
This is just a first shot, and I haven't actually used it much yet, so there are almost certainly bugs, leaked references, etc lurking. I'll probably keep adding to it in the near future. Hope it's useful to someone.
Cheers,
Patrick

_________________________________________________
Python.NET mailing list - PythonDotNet at python.org<mailto:PythonDotNet at python.org>
http://mail.python.org/mailman/listinfo/pythondotnet

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythondotnet/attachments/20130705/732482cc/attachment.html>


More information about the PythonDotNet mailing list