Advertisement
elibelash

Untitled

Jan 1st, 2020
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. //PythonExtensions.cs
  2.     public static class PythonExtensions {
  3.         public static void ExecResource(this PyScope scope, string name) {
  4.             using (Py.GIL()) {
  5.                 scope.Exec(ResourceLoader.Current.GetEmbeddedResourceString(Assembly.GetCallingAssembly(), name, Encoding.UTF8));
  6.             }
  7.         }
  8.  
  9.         public static PyObject GetFunction(this PyScope scope, string funcName) {
  10.             using (Py.GIL()) {
  11.                 return scope.Variables()[funcName];
  12.             }
  13.         }
  14.  
  15.         private static PyScope NumpyInteropScope;
  16.         private static PyObject NumpyConverter;
  17.  
  18.         public static unsafe PyObject ToNumpyNET(this PyScope scope, NDArray nd) {
  19.             using (Py.GIL()) {
  20.                 if (NumpyInteropScope == null) {
  21.                     NumpyInteropScope = Py.CreateScope();
  22.                     NumpyInteropScope.ExecResource("numpy_interop.py");
  23.                     NumpyConverter = NumpyInteropScope.GetFunction("to_numpy");
  24.                 }
  25.  
  26.                 return NumpyConverter.Invoke(new PyLong((long) nd.Unsafe.Address), new PyLong(nd.size * nd.dtypesize), new PyString(nd.dtype.Name.ToLowerInvariant()));
  27.             }
  28.         }
  29.     }
  30.  
  31. //numpy_interop.py
  32. import numpy as np
  33. import ctypes
  34.  
  35. def to_numpy(ptr, bytes, dtype):
  36.     g = (ctypes.c_uint8*(bytes)).from_address(ptr)
  37.     ndarray = np.frombuffer(g, dtype)
  38.     return ndarray
  39.  
  40.  
  41. print("a.py has loaded successfully.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement