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:
- What is a StrongBox[Single]
- How do I create such an object in python to pass to the C# method.
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.
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.
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:
- What is a StrongBox[Single]
- How do I create such an object in python to pass to the C# method.
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.
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.