Pythonnet: Numpy array to C# array

Created on 25 Oct 2017  路  3Comments  路  Source: pythonnet/pythonnet

Environment

  • Pythonnet version: 2.4.0
  • Python version: 3.6 (anaconda)
  • Operating System: Windows 7 (x86)

Details

I am using the code below to use some of the features of pylinac in C#. I would like to know how to convert the dynamic array in to a C# array. In the example below the array structure is 60 rows and 4000 columns.

{[[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]]}

       `PythonEngine.PythonHome = @"C:\Anaconda3";

        using (Py.GIL())
        {
            try
            {
                dynamic pl = Py.Import("pylinac");
                dynamic np = Py.Import("numpy");
                dynamic tlog = pl.TrajectoryLog.from_demo();
                tlog.fluence.gamma.calc_map();
                dynamic array = tlog.fluence.actual.array.astype(np.float32, Py.kw("copy",  false));

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }`

Also when debugging in VS 2017 the process slows down when importing Py.Import("pylinac"), any ideas, should this be in a separate post?

documentation question

Most helpful comment

https://github.com/pythonnet/pythonnet/pull/528 this PR addresses this issue.
Debug is slow due to unoptimized pythonnet Implicit assembly loading technique.

All 3 comments

@bobred the slowdown during import is likely a performance issue with the debugger and nothing to do with pythonnet.
For converting numpy arrays, search this issue tracker. There are multiple methods, e.g. some listed here.:

https://github.com/pythonnet/pythonnet/issues/514

https://github.com/pythonnet/pythonnet/pull/528 this PR addresses this issue.
Debug is slow due to unoptimized pythonnet Implicit assembly loading technique.

We should probably supporting this conversion syntax from ironpython:

http://www.ironpython.info/index.php?title=Typed_Arrays_in_IronPython

Was this page helpful?
0 / 5 - 0 ratings