Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
*.dll
*.exe
*.pdb
pythonnet/dlls/

### JetBrains ###
.idea/
Expand Down
7 changes: 0 additions & 7 deletions NuGet.config

This file was deleted.

91 changes: 91 additions & 0 deletions Python.Loader/Loader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using System.Runtime.InteropServices;
using System.Text;
using System;
using System.IO;
using System.Reflection;
using Mono.Cecil;

namespace Python
{
public class Loader
{
AssemblyDefinition assembly;

static public Loader FromFile(string filename)
{
return new Loader(File.OpenRead(filename));
}

public Loader(Stream stream)
{
assembly = AssemblyDefinition.ReadAssembly(stream, new ReaderParameters
{
InMemory = true,
});
}

public void Remap(string pythonDll)
{
var moduleRef = new ModuleReference(pythonDll);

var module = assembly.MainModule;
module.ModuleReferences.Add(moduleRef);

foreach (var type in module.Types)
{
foreach (var func in type.Methods)
{
if (func.HasPInvokeInfo)
{
var info = func.PInvokeInfo;
if (info.Module.Name == "__Internal")
{
info.Module = moduleRef;
}
}
}
}
}

public Assembly LoadAssembly()
{
using (var stream = new MemoryStream())
{
assembly.Write(stream);
return Assembly.Load(stream.ToArray());
}
}
}

static class Internal
{
public static int Initialize(IntPtr data, int size)
{
try
{
var buf = new byte[size];
Marshal.Copy(data, buf, 0, size);
var str = UTF8Encoding.Default.GetString(buf);

var splitted = str.Split(';');

var dllPath = splitted[0];
var pythonDll = splitted[1];

var loader = Loader.FromFile(dllPath);
loader.Remap(pythonDll);
var assembly = loader.LoadAssembly();

var eng = assembly.GetType("Python.Runtime.PythonEngine");
var method = eng.GetMethod("InternalInitialize");
var res = method.Invoke(null, new object[] { data, size });
return (int)res;
}
catch (Exception exc)
{
Console.WriteLine($"{exc}\n{exc.StackTrace}");
return -1;
}
}
}
}
12 changes: 12 additions & 0 deletions Python.Loader/Python.Loader.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.2" />
</ItemGroup>

</Project>
5 changes: 5 additions & 0 deletions Python.Runtime/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using System;
using System.Runtime.CompilerServices;

[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Python.Test.Embed")]
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,11 @@ public static int GetUnicodeByteLength(IntPtr p)
var len = 0;
while (true)
{
int c = Runtime._UCS == 2
? Marshal.ReadInt16(p, len * 2)
: Marshal.ReadInt32(p, len * 4);
#if UCS2
int c = Marshal.ReadInt16(p, len * 2);
#else
int c = Marshal.ReadInt32(p, len * 4);
#endif

if (c == 0)
{
Expand All @@ -120,9 +122,11 @@ public static int GetUnicodeByteLength(IntPtr p)
/// </remarks>
public static IntPtr Py3UnicodePy2StringtoPtr(string s)
{
return Runtime.IsPython3
? Instance.MarshalManagedToNative(s)
: Marshal.StringToHGlobalAnsi(s);
#if PYTHON2
return Marshal.StringToHGlobalAnsi(s);
#else
return Instance.MarshalManagedToNative(s);
#endif
}

/// <summary>
Expand All @@ -137,9 +141,11 @@ public static IntPtr Py3UnicodePy2StringtoPtr(string s)
/// </returns>
public static string PtrToPy3UnicodePy2String(IntPtr p)
{
return Runtime.IsPython3
? PtrToStringUni(p)
: Marshal.PtrToStringAnsi(p);
#if PYTHON2
return Marshal.PtrToStringAnsi(p);
#else
return PtrToStringUni(p);
#endif
}
}

Expand Down
File renamed without changes.
18 changes: 18 additions & 0 deletions Python.Runtime/Python.Runtime.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<EmbeddedResource Include="resources\clr.py">
<LogicalName>clr.py</LogicalName>
</EmbeddedResource>
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Reflection.Emit" Version="4.6.0" />
</ItemGroup>

</Project>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
38 changes: 31 additions & 7 deletions src/runtime/codegenerator.cs → Python.Runtime/codegenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,40 @@ namespace Python.Runtime
/// </summary>
internal class CodeGenerator
{
private AssemblyBuilder aBuilder;
private ModuleBuilder mBuilder;
private AssemblyBuilder _aBuilder = null;

internal CodeGenerator()
private AssemblyBuilder aBuilder
{
get
{
if (_aBuilder == null)
{
var aname = new AssemblyName { Name = "__CodeGenerator_Assembly" };
var aa = AssemblyBuilderAccess.Run;

_aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa);
}

return _aBuilder;
}
}

private ModuleBuilder _mBuilder = null;
private ModuleBuilder mBuilder
{
var aname = new AssemblyName { Name = "__CodeGenerator_Assembly" };
var aa = AssemblyBuilderAccess.Run;
get
{
if (_mBuilder == null)
{
_mBuilder = aBuilder.DefineDynamicModule("__CodeGenerator_Module");
}

return _mBuilder;
}
}

aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa);
mBuilder = aBuilder.DefineDynamicModule("__CodeGenerator_Module");
internal CodeGenerator()
{
}

/// <summary>
Expand Down
File renamed without changes.
File renamed without changes.
43 changes: 20 additions & 23 deletions src/runtime/converter.cs → Python.Runtime/converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@ internal static IntPtr GetPythonTypeByAlias(Type op)
if (op == int32Type)
return Runtime.PyIntType;

if (op == int64Type && Runtime.IsPython2)
#if PYTHON2
if (op == int64Type)
return Runtime.PyLongType;
#endif

if (op == int64Type)
return Runtime.PyIntType;
Expand Down Expand Up @@ -165,15 +167,7 @@ internal static IntPtr ToPython(object value, Type type)
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
#if NETSTANDARD
return ClassDerivedObject.ToPython(pyderived);
#else
// if object is remote don't do this
if (!System.Runtime.Remoting.RemotingServices.IsTransparentProxy(pyderived))
{
return ClassDerivedObject.ToPython(pyderived);
}
#endif
}

// hmm - from Python, we almost never care what the declared
Expand Down Expand Up @@ -488,8 +482,9 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
return true;

case TypeCode.Int32:
#if PYTHON2
// Trickery to support 64-bit platforms.
if (Runtime.IsPython2 && Runtime.Is32Bit)
if (Runtime.Is32Bit)
{
op = Runtime.PyNumber_Int(value);

Expand All @@ -513,7 +508,8 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
result = ival;
return true;
}
else // Python3 always use PyLong API
#else
// Python3 always use PyLong API
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
Expand All @@ -538,13 +534,14 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
result = (int)ll;
return true;
}
#endif

case TypeCode.Boolean:
result = Runtime.PyObject_IsTrue(value) != 0;
return true;

case TypeCode.Byte:
#if PYTHON3
#if !PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
Expand All @@ -555,7 +552,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
}
goto type_error;
}
#elif PYTHON2
#else
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
Expand Down Expand Up @@ -589,7 +586,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
return true;

case TypeCode.SByte:
#if PYTHON3
#if !PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
Expand All @@ -600,7 +597,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
}
goto type_error;
}
#elif PYTHON2
#else
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
Expand Down Expand Up @@ -634,7 +631,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
return true;

case TypeCode.Char:
#if PYTHON3
#if !PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
Expand All @@ -645,7 +642,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
}
goto type_error;
}
#elif PYTHON2
#else
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
Expand Down Expand Up @@ -753,20 +750,20 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
}
goto type_error;
}

uint ui;
try
try
{
ui = Convert.ToUInt32(Runtime.PyLong_AsUnsignedLong(op));
} catch (OverflowException)
{
// Probably wasn't an overflow in python but was in C# (e.g. if cpython
// longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in
// longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in
// PyLong_AsUnsignedLong)
Runtime.XDecref(op);
goto overflow;
}


if (Exceptions.ErrorOccurred())
{
Expand Down Expand Up @@ -900,7 +897,7 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s

var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(elementType);
IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) :
IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) :
(IList) Activator.CreateInstance(constructedListType);
IntPtr item;

Expand All @@ -921,7 +918,7 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s

items = Array.CreateInstance(elementType, list.Count);
list.CopyTo(items, 0);

result = items;
return true;
}
Expand Down
File renamed without changes.
File renamed without changes.
Loading