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

2024/9/28 1:18:10

I'm having the following static C# method

public static bool TryParse (string s, out double result)

which I would like to call from Python using the Python NET package.

import clr
from System import Double
r0 = Double.IsNaN(12.3) # worksr1, 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

Any idea?

Update

I found the following answer, see https://stackoverflow.com/a/19600349/7556646.

CPython using PythonNet does basically the same thing. The easy way todo out parameters is to not pass them and accept them as extra returnvalues, and for ref parameters to pass the input values as argumentsand accept the output values as extra return values.

This would claim that r1, d1 = Double.TryParse("12.3") should work, but it doesn't.

Answer

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.))
https://en.xdnf.cn/q/71392.html

Related Q&A

ValueError: Length of passed values is 7, index implies 0

I am trying to get 1minute open, high, low, close, volume values from bitmex using ccxt. everything seems to be fine however im not sure how to fix this error. I know that the index is 7 because there …

What is pythons strategy to manage allocation/freeing of large variables?

As a follow-up to this question, it appears that there are different allocation/deallocation strategies for little and big variables in (C)Python. More precisely, there seems to be a boundary in the ob…

Why is cross_val_predict so much slower than fit for KNeighborsClassifier?

Running locally on a Jupyter notebook and using the MNIST dataset (28k entries, 28x28 pixels per image, the following takes 27 seconds. from sklearn.neighbors import KNeighborsClassifierknn_clf = KNeig…

Do I need to do any text cleaning for Spacy NER?

I am new to NER and Spacy. Trying to figure out what, if any, text cleaning needs to be done. Seems like some examples Ive found trim the leading and trailing whitespace and then muck with the start/st…

Hi , I have error related to object detection project

I have error related to simple object detection .output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] IndexError: invalid index to scalar variable.import cv2.cv2 as cv import…

What is the fastest way to calculate / create powers of ten?

If as the input you provide the (integer) power, what is the fastest way to create the corresponding power of ten? Here are four alternatives I could come up with, and the fastest way seems to be usin…

How to disable date interpolation in matplotlib?

Despite trying some solutions available on SO and at Matplotlibs documentation, Im still unable to disable Matplotlibs creation of weekend dates on the x-axis.As you can see see below, it adds dates to…

Continuous error band with Plotly Express in Python [duplicate]

This question already has answers here:Plotly: How to make a figure with multiple lines and shaded area for standard deviations?(5 answers)Closed 2 years ago.I need to plot data with continuous error …

How to preprocess training set for VGG16 fine tuning in Keras?

I have fine tuned the Keras VGG16 model, but Im unsure about the preprocessing during the training phase.I create a train generator as follow:train_datagen = ImageDataGenerator(rescale=1./255) train_ge…

Using Python like PHP in Apache/Windows

I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but Im confused about it:This is a sample configuration I found for web.py:LoadModule wsgi_module modul…