Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using Ebby.Reflection;
- using NumSharp;
- using NumSharp.Generic;
- using Python.Runtime;
- namespace WizardStuff.Python {
- public static class PythonExtensions {
- public static void ExecResource(this PyScope scope, string name) {
- using (Py.GIL()) {
- scope.Exec(ResourceLoader.Current.GetEmbeddedResourceString(Assembly.GetCallingAssembly(), name, Encoding.UTF8));
- }
- }
- public static void ExecFile(this PyScope scope, string path) {
- if (!File.Exists(path))
- throw new FileNotFoundException(path);
- var txt = File.ReadAllText(path, Encoding.UTF8);
- using (Py.GIL()) {
- var script = PythonEngine.Compile(txt, new FileInfo(path).FullName, RunFlagType.File);
- scope.Execute(script)?.Dispose();
- }
- }
- public static PyObject GetFunction(this PyScope scope, string funcName) {
- using (Py.GIL()) {
- return scope.Variables()[funcName];
- }
- }
- private static PyScope NumpyInteropScope;
- private static PyObject NumpyConverter;
- public static PyObject ToNumpyNET<T>(this NDArray<T> nd) where T : unmanaged {
- return ToNumpyNET((NDArray) nd);
- }
- public static unsafe PyObject ToNumpyNET(this NDArray nd) {
- using (Py.GIL()) {
- if (NumpyInteropScope == null) {
- NumpyInteropScope = Py.CreateScope();
- NumpyInteropScope.ExecResource("numpy_interop.py");
- NumpyConverter = NumpyInteropScope.GetFunction("to_numpy");
- }
- return NumpyConverter.Invoke(
- new PyLong((long) nd.Unsafe.Address),
- new PyLong(nd.size * nd.dtypesize),
- new PyString(nd.dtype.Name.ToLowerInvariant()),
- new PyTuple(nd.shape.Select(dim => (PyObject) new PyLong(dim)).ToArray())
- );
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement