Python to C# StongBox[Single]

Question:

I’ve used IronPython to add a reference to a C# dll. I’m attempting to use a method in the DLL which requires an argument of type:

out float tempValue

When I pass a python float object to the method I get the following traceback:

Traceback (most recent call last):
  File "MeasurementComputing.py", line 20, in <module>
TypeError: expected StrongBox[Single], got float

My questions are:

  1. What is a StrongBox[Single]
  2. How do I create such an object in python to pass to the C# method.
Asked By: Matt Albert

||

Answers:

In order to have a proper target for the out parameter you have to explicitly create a clr reference (StrongBox serves as that reference/value wrapper) in IronPython, as there is no out keyword on the caller side (like in C#) that would allow you to do so.

This could look like:

import clr
import System
tempValue = clr.Reference[System.Single]()

Directly creating the StrongBox instance should also work.

Please be aware that you could also consume methods, that have only out parameters, not passing anything but receiving a tuple as explained here.

Answered By: Simon Opelt

Another option is to "move" the out parameter(s) to the left side of the statement.
For example the TryParse C# function in the System.Decimal class looks like this:

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

You can call it from Python in the following way:

from System import Decimal

OK, myDecimal = Decimal.TryParse('1.2345')

This way you can avoid using the StrongBox.

Answered By: Gábor Kocsis
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.