Trouble compiling some decompiled C# code
I was decompiling an open-source project (because the source for the la开发者_JS百科test version hasn't been released yet). Using RedGate's Reflector tool, it gave me this block of code:
if(somecondition == true)
{
ref Vector3i vectoriRef;
float num17 = length - num;
Vector3i end = vectori3;
(vectoriRef = (Vector3i) &end)[1] = vectoriRef[1] - ((int) num17);
}
somecondition
is a boolean. length
and num
are floats defined outside the code. vectori3
is also defined outside the code and is of type Vector3i. The type Vector3i is essentially this code, but with x, y, and z stored as integers.
When I try to compile this decompiled code, I get the following errors:
- Line 2: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
- Line 3: ; expected
- Line 3: Invalid expression term 'ref'
- Line 6: 'Vector3i' is a 'type' but is used like a 'variable'
Any thoughts on how I can fix this code so it compiles correctly and does whatever it was intended to do?
UPDATE: It turns out the source is available in their repository, but you have to follow a maze of links and clues to even find it. Thanks to everyone who posted!
The code uses a mutable value type, which is a "worst practice" in C#. The code that we generate for mutable value types can be quite difficult to correctly analyze and decompile; apparently you have run into a bug in the decompilation engine. C# does not support the given syntax. (It could in the future; I have written a prototype of "ref locals" and it works quite nicely, but it is not clear that the feature is actually valuable enough to customers to warrant a full design and implementation.)
Read the code carefully and you'll see what it is doing: it's making a copy of vectori3 into end, then obtaining a ref to end (remember, the "this" of a call to a value type is always a ref to a variable because the call might be mutating the contents of that variable.) Then its using the ref to mutate the variable. But why?? This code doesn't make any sense. Why would you make a local copy of a variable and then mutate the copy, and then discard the mutated copy?
I suspect that you've not only found a bug in the decompiler; you may have also found a bug in the code.
At first glance
if (somecondition)
{
vectori3[1] -= (int)(length - num);
}
I'm not clear about the explicit reference syntax - I've never seen that before, and can't get VS to accept it - but the last line splits out into
vectoriRef = (Vector3i) &end;
vectoriRef[1] = vectoriRef[1] - ((int) num17);
精彩评论