【问题标题】:Pythonnet cannot convert object to target typePythonnet 无法将对象转换为目标类型
【发布时间】:2023-01-05 19:40:18
【问题描述】:

使用 pythonnet,我从我的 C# 脚本调用一个 Python 函数,它返回一个对象。从 Python 函数获得结果后,我希望能够将此 Python 对象强制转换/转换为 C# 用户定义的类。我尝试使用 AsManagedObject (Type t) 和 As<T> () 函数,但在运行时出现错误 -

无法将对象转换为目标类型 内部异常 PythonException:'Result' 值无法转换为 Models.Result

我可以使用一些帮助将 PyObjects 转换为 C# 用户定义的类型。

Python -

#Result.py
class Result:
    def __init__(self, Sum) -> None:
        self.Sum = Sum

#Main.py
from Result import Result
def add(inputCsharp) -> Result:
     result = Result(inputCsharp.Input1 + inputCsharp/input2)
     return result

C# -

//Result.cs
public class Result
{
    public int Sum { get; set; }
}

//Program.cs
using (Py.GIL())
{
    using (var scope = Py.CreateScope())
    {
        dynamic obj = Py.Import(@"Main");

        var inputCsharp = new Input() 
        {
            Input1 = 2,
            Input2 = 3
        };
       
        var result = obj.add(inputCsharp.ToPython());
        var t = (Result)result.AsManagedObject(typeof(Result)); //here it is throwing an error
    }
}

【问题讨论】:

    标签: python c# python.net


    【解决方案1】:

    要将 Python 对象转换为 C# 对象,您可以尝试以下步骤:

    使用 PythonEngine 类的 GetManagedObject 方法将对象检索为托管对象。 使用 Marshal.PtrToStructure 方法将托管对象转换为 C# 对象。 以下是如何执行此操作的示例:

    using Python.Runtime;
    using System.Runtime.InteropServices;
    
    // Assume that result is the Python object returned by the Python function
    IntPtr ptr = PythonEngine.PythonEngine.GetManagedObject(result);
    
    // Assume that Result is the C# class you want to convert the Python object to
    Result csharpResult = (Result)Marshal.PtrToStructure(ptr, typeof(Result));
    

    请记住,这仅在 Python 对象是与 C# 类兼容的类型时才有效。如果类型不兼容,您可能会在运行时遇到异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多