问题
I find it really confusing to understand pass by reference in c#. In my code I have function which takes two parameters
private bool SerialUnEscape(byte serialData, ref byte serialResult)
{
if (((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) ||
((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_END)) {
serialEscaped = false;
serialResult = 0;
return (true);
}
} else if (serialEscaped) {
if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_ESCAPE_START) {
serialResult = (int)SerialProcessValue.SERIAL_PACKET_START;
serialEscaped = false;
return (true);
}
} else {
serialResult = serialData;
return (true);
}
}
I am calling the function with a reference as serialDataLsb & serialDataMsb.
Now my confusion is about, what would be the value of serialDataLsb or serialDataMsb,
Does it get the value of serialResult ??
for (i = 0; i < serialElements; i++) {
serialDataLsb = 0;
serialDataMsb = 0;
while (serialBufferWalk < serialIndex) {
if (SerialUnEscape(serialBuffer[serialBufferWalk++], ref serialDataLsb)) {
break;
}
}
while (serialBufferWalk < serialIndex) {
if (SerialUnEscape(serialBuffer[serialBufferWalk++], ref serialDataMsb)) {
break;
}
}
serialElementData[i] = (UInt16)(serialDataLsb + (serialDataMsb << 8));
}
and i need to port this code into python, 1) how can i implement the pass by reference in python
I tried using this
while serialBufferWalk < serialIndex:
if self.SerialUnEscape(serialBuffer[serialBufferWalk += 1],serialDataLsb):
break
while serialBufferWalk < serialIndex:
if self.SerialUnEscape(serialBuffer[serialBufferWalk += 1],serialDataLsb):
break
回答1:
If you really want to imitate pass-by-reference instead of changing your code to return the value, you can wrap the primitive you want to change in an object. For simplicity, I used a list:
def change_reference(byteContainer):
byteContainer[0] = 42
b = 123
print(b) # Prints 123
# Copy the data into the container list.
container = [b]
# Pass a pointer to that list into the function.
change_reference(container)
# Take the value out of the container.
b = container[0]
print(b) # Prints 42
This makes your function really confusing though. What you should really do is include the modified byte in the return value:
def test_and_subtract(v):
if v == 1:
return (v - 1, True)
return (v - 2, False)
v = 1
v, b = test_and_subtract(v)
print(v) # 0
print(b) # True
v = 5
v, b = test_and_subtract(v)
print(v) # 3
print(b) # False
Here return (v - 1, True) is putting both results into a tuple, and b, v is removing them from that tuple.
来源:https://stackoverflow.com/questions/31728934/trouble-understanding-pass-by-reference