Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //PythonExtensions.cs
- 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 PyObject GetFunction(this PyScope scope, string funcName) {
- using (Py.GIL()) {
- return scope.Variables()[funcName];
- }
- }
- private static PyScope NumpyInteropScope;
- private static PyObject NumpyConverter;
- public static unsafe PyObject ToNumpyNET(this PyScope scope, 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()));
- }
- }
- }
- //numpy_interop.py
- import numpy as np
- import ctypes
- def to_numpy(ptr, bytes, dtype):
- g = (ctypes.c_uint8*(bytes)).from_address(ptr)
- ndarray = np.frombuffer(g, dtype)
- return ndarray
- print("a.py has loaded successfully.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement