从 C# 调用带有 out 参数的重写方法到 python使用 pythonnet

问题描述

在 C# 中,我定义了一个带有 out 参数的方法的接口。 我在 python 中实现了这个接口,现在我想从 C# 调用这个方法。 (我用的是pythonnet)

我看到的是,没有 out 参数的方法可以正常工作,但是带有 out 参数的方法会引发访问冲突。

我知道在 pythonnet 中 out 参数的处理方式不同:您返回一个元组,首先是返回值,第二个元组项是 out 参数。

不支持吗?

使用 pythonnet 2.5.2(最新)和 python 3.8.3

我的 C# 代码

public interface IMyInterface
{
    string MyMethod_Out(string name,out int index);
    string MyMethod(string name);
}

public class MyServer
{
    public void CallMyMethod_Out(IMyInterface myInterface)
    {
        Console.WriteLine("C#.CallMyMethod_Out: before MyMethod_Out");
        int index = 1;
        myInterface.MyMethod_Out("myclient",out index);
        Console.WriteLine($"C#:CallMyMethod_Out: after MyMethod_Out: index:{index}");
    }
    
    public void CallMyMethod(IMyInterface myInterface)
    {
        Console.WriteLine("C#.CallMyMethod: before MyMethod");
        myInterface.MyMethod("myclient");
        Console.WriteLine($"C#:CallMyMethod: after MyMethod");
    }

    public void DoSomething()
    {
        Console.WriteLine("C#.DoSomething");
    }
}

我的 Python 代码

import clr
import sys

sys.path.append('some_dir')
clr.AddReference("ClassLibrary1")

from ClassLibrary1 import IMyInterface,MyServer

class MyInterfaceImpl(IMyInterface):
    __namespace__ = "ClassLibrary1"

    def MyMethod_Out(self,name,index):
        print("Python.MyInterfaceImpl.MyMethod_Out")
        other_index = 101
        return ('MyName',other_index)

    def MyMethod(self,name):
        print("Python.MyInterfaceImpl.MyMethod")
        return 'MyName'

print('\nCall regular C# function')
my_server = MyServer()
my_server.DoSomething()

my_interface_impl = MyInterfaceImpl()

print('\nCall without out param')
my_server.CallMyMethod(my_interface_impl)

print('\nCall with out param')
my_server.CallMyMethod_Out(my_interface_impl) # Access Violation 0xC0000005

输出

Call regular C# function
C#.DoSomething

Call without out param
C#.CallMyMethod: before MyMethod
Python.MyInterfaceImpl.MyMethod
C#:CallMyMethod: after MyMethod

Call with out param
C#.CallMyMethod_Out: before MyMethod_Out
Process finished with exit code -1073741819 (0xC0000005)

我期望:

Call with out param
C#.CallMyMethod_Out: before MyMethod_Out
Python.MyInterfaceImpl.MyMethod_Out
C#:CallMyMethod_Out: after MyMethod_Out: index:101

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)