Advertisement
elibelash

Untitled

Jan 15th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. using System.IO;
  2. using System.Linq;
  3. using System.Reflection;
  4. using System.Text;
  5. using Ebby.Reflection;
  6. using NumSharp;
  7. using NumSharp.Generic;
  8. using Python.Runtime;
  9.  
  10. namespace WizardStuff.Python {
  11.     public static class PythonExtensions {
  12.         public static void ExecResource(this PyScope scope, string name) {
  13.             using (Py.GIL()) {
  14.                 scope.Exec(ResourceLoader.Current.GetEmbeddedResourceString(Assembly.GetCallingAssembly(), name, Encoding.UTF8));
  15.             }
  16.         }
  17.  
  18.         public static void ExecFile(this PyScope scope, string path) {
  19.             if (!File.Exists(path))
  20.                 throw new FileNotFoundException(path);
  21.             var txt = File.ReadAllText(path, Encoding.UTF8);
  22.  
  23.             using (Py.GIL()) {
  24.                 var script = PythonEngine.Compile(txt, new FileInfo(path).FullName, RunFlagType.File);
  25.                 scope.Execute(script)?.Dispose();
  26.             }
  27.         }
  28.  
  29.         public static PyObject GetFunction(this PyScope scope, string funcName) {
  30.             using (Py.GIL()) {
  31.                 return scope.Variables()[funcName];
  32.             }
  33.         }
  34.  
  35.         private static PyScope NumpyInteropScope;
  36.         private static PyObject NumpyConverter;
  37.  
  38.         public static PyObject ToNumpyNET<T>(this NDArray<T> nd) where T : unmanaged {
  39.             return ToNumpyNET((NDArray) nd);
  40.         }
  41.  
  42.         public static unsafe PyObject ToNumpyNET(this NDArray nd) {
  43.             using (Py.GIL()) {
  44.                 if (NumpyInteropScope == null) {
  45.                     NumpyInteropScope = Py.CreateScope();
  46.                     NumpyInteropScope.ExecResource("numpy_interop.py");
  47.                     NumpyConverter = NumpyInteropScope.GetFunction("to_numpy");
  48.                 }
  49.  
  50.                 return NumpyConverter.Invoke(
  51.                     new PyLong((long) nd.Unsafe.Address),
  52.                     new PyLong(nd.size * nd.dtypesize),
  53.                     new PyString(nd.dtype.Name.ToLowerInvariant()),
  54.                     new PyTuple(nd.shape.Select(dim => (PyObject) new PyLong(dim)).ToArray())
  55.                 );
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement