dereferencing a pointer in a function block

tvm
2018-03-06
2018-03-08
  • tvm - 2018-03-06

    I'm having some issues with dereferencing a pointer in a function block. I've tried to simplify the issue down to the following code:

    VAR
       VarPlaceholder:         ARRAY[1..255] OF BYTE;
       ptrPlaceholder:         POINTER TO ARRAY[1..255] OF BYTE;
       VarFloatingPoint:      REAL;
       ptrFloatingPoint:      POINTER TO REAL;
    END_VAR
    ptrPlaceholder:= ADR(VarPlaceholder);   //get a pointer to a variable of type ARRAY[1..255] OF BYTE
    ptrFloatingPoint:= ptrPlaceholder;      //pass the pointer to a different type of pointer, POINTER TO REAL
    VarFloatingPoint:= ptrFloatingPoint^;      //dereference the pointer as a REAL
    

    This code works as expected if I put it in a test program. If I change the values of the array, I get different REAL numbers in VarFloatingPoint.

    However, if I put the exact same code in a function block and call it from the same test program, I will get an access violation exception on the third line, where it dereferences the pointer. Line 1 does get a valid pointer, and Line 2 does copy that pointer over to ptrFloatingPoint (see attached image).

    Is there something different about the way a pointer is handled in a function block?

    IMG: pointer exception.PNG

     
  • josepmariarams - 2018-03-07

    Hi.

    It could be an alignment trouble.

    Try to create an array of 64 reals. Point to him an pointer to array of 254 bytes.

    Buffer: array [0..63] of real.

    Bytes:pointer to array[0..255] of byte....

    Bytes:=adr(buffer).

    Then the array of bytes will be aligned as an real.

     
  • yannickasselin1 - 2018-03-07

    Instead of using a POINTER TO ARRAY[1..255] OF BYTE; just use a pointer to BYTE and pass it the array.
    You will still be able to iterate through the array in your FB.

    This is what I do in TwinCAT and it works fine.
    I tried using variable arrays but found some bugs. See this post: l viewtopic.php?t=7558#p17267 l

     
  • josepmariarams - 2018-03-07

    You are right Yannick

     
  • tvm - 2018-03-08

    Thank you for the replies. Yes, it was an alignment problem. If I get a pointer to BYTE, it can only be dereferenced as a WORD type if the address is divisible by 2, and as a DWORD type if the address is divisible by 4. So depending on where the pointer landed, it would work or not work.
    Tim

     

Log in to post a comment.