Python NET call C# method which has a return value and an out parameter

随声附和 提交于 2019-12-04 19:14:25

I had to address a similar problem recently with using Python for .NET, let me share with you what I have found out.

You need to pass as many arguments as the method requires to. Since the concept of out arguments (= passed by refence) doesn't apply to Python, the trick is to pass some dummy arguments of the expected type.

The method call is going to return first the values that it is supposed to return, and the out values.

For my use case, the C# method I was calling did not return anything originally (void method), yet, the Python call returned first None and then the out values I was after, which is the expected behaviour as stated here.

Your first attempt could not work because you pass only one argument, while the method expects two, be they out or ref arguments.

r1, d1 = Double.TryParse("12.3")

Your second attempt could not work either because the type of the dummy argument does not match with the type expected by the method, in that case Double.

d2 = 0.0
r2, d2 = Double.TryParse("12.3", d)

This will do the trick:

import clr
from System import Double
dummy_out = Double(0.)
returned_val, real_out = Double.TryParse("12.3", dummy_out)

You can observe that this last line does not have any effect on dummy_out by checking its id before and after the call.

Hence, a shorter version of the code you need would be:

returned_val, real_out = Double.TryParse("12.3", Double(0.))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!