Closed pitakp closed 1 year ago
Hi @pitakp,
I tested it with byte arrays, but I suppose for other types shorter than Int32 it demonstartes the same behaviour.
That's correct. This issue has less to do with arrays than with numbers passed from the script engine to the host.
ClearScript narrows each JavaScript number to the smallest signed .NET numeric type that retains full precision, but it doesn't go narrower than Int32
for reasons related to convenience and the complex behavior of C# method binding.
Unfortunately, as you've noticed, this solution can result in unexpected behavior. Some numeric parameter types require special handling in some cases, and HostFunctions
provides helpers for that:
elems[0] = host.toByte(32);
Note that this isn't quite the same as casting. The cast
method is meant to return a value that is of use to script code. It provides access to .NET features such as interfaces and user-defined conversions, whereas toByte
et al are specifically for passing numbers to the host. The objects they return are not otherwise useful.
Good luck!
Thank you for your explanation and showing a solution! I completely overlooked the host.toByte(...)
method, and I didn't know the difference between cast
and toByte
methods. Your comment explained the intended behaviour very well.
Hi,
I tried to create .NET arrays from Javascript code (V8 engine) and change element values, however it always fails. It seems that the byte value is always converted to Int32 value but such a value is refused when being assigned into a byte array element (even if I use explicit cast, see example). I tested it with byte arrays, but I suppose for other types shorter than Int32 it demonstartes the same behaviour. Interestingly, my custom method for updating an array (SetByteElement) requires byte value, but it accepts Javascript integer values without any conversion problem. Here is the code (failing code is commented-out):
Here is stack trace for eror on line
elems[0] = 32
: