Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom types #283

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
49 changes: 49 additions & 0 deletions src/CSnakes.Runtime/PyObjectTypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using CSnakes.Runtime.Python;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text;

namespace CSnakes.Runtime;
internal partial class PyObjectTypeConverter
Expand Down Expand Up @@ -36,8 +37,56 @@ public static object PyObjectToManagedType(PyObject pyObject, Type destinationTy
return new PyBuffer(pyObject);
}

// Need to find a better way to detect that a PyObject is a class instance
if (pyObject.GetPythonType().ToString().StartsWith("<class"))
{
var properties = destinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
var instance = Activator.CreateInstance(destinationType) ?? throw new InvalidOperationException($"Failed to create instance of {destinationType}");
foreach (var property in properties)
{
if (property.Name == "Self")
{
property.SetValue(instance, pyObject);
continue;
}

var pythonNameAttribute = property.GetCustomAttribute<PythonNameAttribute>();
string attrName = pythonNameAttribute?.Name ?? ToSnakeCase(property.Name);
var value = pyObject.GetAttr(attrName);
property.SetValue(instance, value.As(property.PropertyType));
}
return instance;
}

throw new InvalidCastException($"Attempting to cast {destinationType} from {pyObject.GetPythonType()}");
}

private static string ToSnakeCase(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}

var stringBuilder = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
if (char.IsUpper(value[i]))
{
if (i > 0)
{
stringBuilder.Append('_');
}
stringBuilder.Append(char.ToLower(value[i]));
}
else
{
stringBuilder.Append(value[i]);
}
}

return stringBuilder.ToString();
}

record DynamicTypeInfo(ConstructorInfo ReturnTypeConstructor, ConstructorInfo? TransientTypeConstructor = null);
}
6 changes: 6 additions & 0 deletions src/CSnakes.Runtime/PythonNameAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace CSnakes.Runtime;
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class PythonNameAttribute(string name) : Attribute
{
public string Name { get; } = name;
}
Loading
Loading