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

Patrick Stewart patstew at gmail.com
Tue Jul 2 11:35:10 CEST 2013


Hi,
Just thought I'd send a heads up to say I've made some modifications to
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythondotnet/attachments/20130702/5e253e10/attachment.html>


More information about the PythonDotNet mailing list