Saturday, 14 September 2013

Doing mathematical operations on operands of various sizes, only known at runtime

Doing mathematical operations on operands of various sizes, only known at
runtime

I'm writing a small virtual computer, complete with its own instruction
set. The thing that's giving me problems is the arithmetical instructions
(add, mul, div, and so forth) because I want them to be able to work on
operands of various different sizes (8, 16, 32, and 64-bit signed and
unsigned integers, and 32 and 64-bit floating points - essentially, every
numeric C# primitive type). The type of the operands aren't known until
runtime.
I'm not sure of any elegant way to do this in C#, though. The operands,
which usually live on a special stack type I'm writing, will be returned
by a Pop method, but, as far as I know, methods can only have one return
type.
Likewise, in the methods that perform the arithmetical instructions,
having different operand sizes means I'd need to write a pretty unruly
switch block.
I've seen the dynamic keyword, but I've heard it was better suited for
interop with IronRuby/IronPython.
Is there any way I can solve this elegantly, without resorting to switch
blocks or boxing everything in objects?

No comments:

Post a Comment