Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text.RegularExpressions;
- namespace ConsoleApp
- {
- class Program
- {
- class FunctionLoader
- {
- [DllImport("Kernel32.dll")]
- private static extern IntPtr LoadLibrary(string path);
- [DllImport("Kernel32.dll")]
- private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
- public static T LoadFunction<T>(string dllPath, string functionName)
- {
- var hModule = LoadLibrary(dllPath);
- var functionAddress = GetProcAddress(hModule, functionName);
- return (T) (object) Marshal.GetDelegateForFunctionPointer(functionAddress, typeof(T));
- }
- }
- private delegate void XRefDelegate(IntPtr pyobject);
- private delegate IntPtr PyLong_FromLong(IntPtr pyobject);
- private delegate IntPtr PyErr_Occurred();
- static void Main(string[] args)
- {
- //MessageBox = (MessageBoxDelegate)
- var pydll = FindPythonDll(36);
- FunctionLoader.LoadFunction<Action>(pydll, "Py_Initialize")();
- var incr = FunctionLoader.LoadFunction<XRefDelegate>(pydll, "Py_IncRef");
- var dcr = FunctionLoader.LoadFunction<XRefDelegate>(pydll, "Py_DecRef");
- var created_int_object = FunctionLoader.LoadFunction<PyLong_FromLong>(pydll, "PyLong_FromLong")((IntPtr) 1098080);
- var checkerFunc = FunctionLoader.LoadFunction<PyErr_Occurred>(pydll, "PyErr_Occurred");
- void checkError() {
- if (checkerFunc() != IntPtr.Zero)
- throw new Exception();
- }
- var a = Refcount(created_int_object);
- checkError();
- incr(created_int_object);
- var b = Refcount(created_int_object);
- Debug.Assert(a+1==b);
- dcr(created_int_object);
- b = Refcount(created_int_object);
- Debug.Assert(a==b);
- }
- internal static unsafe long Refcount(IntPtr op)
- {
- var p = (void*)op;
- if ((void*)0 == p)
- {
- return 0;
- }
- return !Environment.Is64BitProcess ? (*(int*)p) : (*(long*)p);
- }
- static string FindPythonDll(int version) {
- return Environment.GetEnvironmentVariable("PATH")
- .Split(';')
- .Where(p => Regex.IsMatch(p, @"[Pp]ython\d\d[/\\]?$"))
- .SelectMany(p => Directory.GetFiles(p, "python*.dll").Where(pa => Regex.IsMatch(pa, $@"[Pp]ython{version}\.dll")))
- .Single();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement