Python NET 调用具有 return 值和输出参数的 C# 方法
Python NET call C# method which has a return value and an out parameter
我有以下静态 C# 方法
public static bool TryParse (string s, out double result)
我想使用 Python NET 包从 Python 调用它。
import clr
from System import Double
r0 = Double.IsNaN(12.3) # works
r1, d1 = Double.TryParse("12.3") # fails! TypeError: No method matches given arguments. This works in IronPython.
d2 = 0.0
r2, d2 = Double.TryParse("12.3", d2) # fails! TypeError: No method matches given arguments
有什么想法吗?
更新
我找到了以下答案,参见 。
CPython using PythonNet does basically the same thing. The easy way to
do out parameters is to not pass them and accept them as extra return
values, and for ref parameters to pass the input values as arguments
and accept the output values as extra return values.
这会声称 r1, d1 = Double.TryParse("12.3")
应该有效,但实际上无效。
我最近在使用 Python for .NET 时不得不解决类似的问题,让我与您分享我的发现。
您需要根据方法的需要传递尽可能多的参数。由于 out
参数的概念(= 通过引用传递)不适用于 Python,诀窍是传递一些预期类型的 虚拟参数 。
方法调用将首先 return 它应该 return、 和 out
值的值。
对于我的用例,我调用的 C# 方法最初没有 return 任何东西(无效方法),但是 Python 调用首先 returned None
然后是我所追求的 out
值,这是 here.
所述的预期行为
您的第一次尝试失败,因为您只传递了一个参数,而该方法需要两个参数,无论是 out
还是 ref
个参数。
r1, d1 = Double.TryParse("12.3")
你的第二次尝试也失败了,因为伪参数的类型与方法期望的类型不匹配,在这种情况下 Double
.
d2 = 0.0
r2, d2 = Double.TryParse("12.3", d)
这样做就可以了:
import clr
from System import Double
dummy_out = Double(0.)
returned_val, real_out = Double.TryParse("12.3", dummy_out)
通过检查调用前后的 id
,您可以观察到最后一行对 dummy_out
没有任何影响。
因此,您需要的代码的较短版本是:
returned_val, real_out = Double.TryParse("12.3", Double(0.))
我有以下静态 C# 方法
public static bool TryParse (string s, out double result)
我想使用 Python NET 包从 Python 调用它。
import clr
from System import Double
r0 = Double.IsNaN(12.3) # works
r1, d1 = Double.TryParse("12.3") # fails! TypeError: No method matches given arguments. This works in IronPython.
d2 = 0.0
r2, d2 = Double.TryParse("12.3", d2) # fails! TypeError: No method matches given arguments
有什么想法吗?
更新
我找到了以下答案,参见 。
CPython using PythonNet does basically the same thing. The easy way to do out parameters is to not pass them and accept them as extra return values, and for ref parameters to pass the input values as arguments and accept the output values as extra return values.
这会声称 r1, d1 = Double.TryParse("12.3")
应该有效,但实际上无效。
我最近在使用 Python for .NET 时不得不解决类似的问题,让我与您分享我的发现。
您需要根据方法的需要传递尽可能多的参数。由于 out
参数的概念(= 通过引用传递)不适用于 Python,诀窍是传递一些预期类型的 虚拟参数 。
方法调用将首先 return 它应该 return、 和 out
值的值。
对于我的用例,我调用的 C# 方法最初没有 return 任何东西(无效方法),但是 Python 调用首先 returned None
然后是我所追求的 out
值,这是 here.
您的第一次尝试失败,因为您只传递了一个参数,而该方法需要两个参数,无论是 out
还是 ref
个参数。
r1, d1 = Double.TryParse("12.3")
你的第二次尝试也失败了,因为伪参数的类型与方法期望的类型不匹配,在这种情况下 Double
.
d2 = 0.0
r2, d2 = Double.TryParse("12.3", d)
这样做就可以了:
import clr
from System import Double
dummy_out = Double(0.)
returned_val, real_out = Double.TryParse("12.3", dummy_out)
通过检查调用前后的 id
,您可以观察到最后一行对 dummy_out
没有任何影响。
因此,您需要的代码的较短版本是:
returned_val, real_out = Double.TryParse("12.3", Double(0.))