Understanding of problems is transmitted by reference.

It is very difficult for me to understand how to get through the link in C #. In my code, I have a function that 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 call a function with a link like serialDataLsb and serialDataMsb .

Now, my confusion about what will be the value of serialDataLsb or serialDataMsb , Does the value 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 in python, 1) how can I implement 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 
+5
source share
1 answer

If you really want to simulate a pass-by-reference instead of changing the code to return a value, you can transfer the primitive that you want to change in the 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. What you really have to do is include the changed 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) places both results in a tuple, and b, v removes them from this tuple.

0
source

All Articles