I am trying to return a structure from a Procedure and then use it in a nested equation.
I've done this in VB6 given Functions can return types or structures or arrays and the 'Exit Function' command does not change the function's return value.
Code: Select all
Public Type cri ' Define complex rectangular(real/imag) or polar(mag/ang)
r As Double ' real or mag
i As Double ' imag or ang
End Type
Public Function cSum(x As cri, y As cri) As cri
' Returns complex sum
cSum.r = x.r + y.r
cSum.i = x.i + y.i
Exit Function ' shown but not needed
End Function
Unless someone can explain how to preserve the eax value after calling FreeMemory(*p) in cSum2(), I am forced to use the 3 parameter Procedure cSum3().
Essentially, I would prefer not to pass a pointer to the Result as a parameter.
And I also don't want to use a Global *p.cri, which works fine but is harder to manage.
Any ideas?
Code: Select all
Structure cri ; Define complex rectangular(real/imag) or polar(mag/ang)
r.d ; real or mag
i.d ; imag or ang
EndStructure
Define.cri A,B,*C = AllocateMemory(SizeOf(cri))
Procedure.i cSum2(*x.cri, *y.cri)
; Return complex sum of 2 complex numbers
; Returns eax Structured Pointer Memory.
Protected.cri *p = AllocateMemory(SizeOf(cri))
*p\r = *x\r + *y\r
*p\i = *x\i + *y\i
Debug "*p in cSum2() = " + Str(*p)
!MOV eax,[p.p_p]
;FreeMemory(*p) ; eax is correct if uncommented, but creates memory leak!
ProcedureReturn ; eax preserved
EndProcedure
Procedure.i cSum3(*x.cri, *y.cri, *r.cri)
; Return complex sum of 2 complex numbers
; Returns Pointer to Structured memory.
*r\r = *x\r + *y\r
*r\i = *x\i + *y\i
ProcedureReturn *r
EndProcedure
A\r = 1: A\i = 1
B\r = 2: B\i = 2
*C\r = 0: *C\i = 0
Debug "--- Using cSum2() ---"
Debug "*C = " + Str(*C)
*C = cSum2(A,B)
Debug "[1+1i] + [2+2i] = " + StrD(*C\r,1) + " + " +StrD(*C\i,1) + "i"
Debug "--- Using cSum3() ---"
*C = cSum3(A,B,*C)
Debug "[1+1i] + [2+2i] = " + StrD(*C\r,1) + " + " +StrD(*C\i,1) + "i"
A\r = 1: A\i = 1
B\r = 2: B\i = 2
*C\r = 0: *C\i = 0
Debug "--- Using nested call of cSum2() ---"
*C = cSum2(A, cSum2(A,B))
Debug "[1+1i] + ([1+1i] + [2+2i]) = " + StrD(*C\r,1) + " + " +StrD(*C\i,1) + "i"
Debug "*C = " + Str(*C)
A\r = 1: A\i = 1
B\r = 2: B\i = 2
*C\r = 0: *C\i = 0
Debug "--- Using nested call of cSum3() ---"
*C = cSum3(A, cSum3(A,B,*C),*C)
Debug "[1+1i] + ([1+1i] + [2+2i]) = " + StrD(*C\r,1) + " + " +StrD(*C\i,1) + "i"
Debug "*C = " + Str(*C)
If *c
FreeMemory(*C)
EndIf