1

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

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

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

这不支持吗?

将 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
4

0 回答 0