Amir wrote:
> I have a code like this:
>
> var
> rgsa: Array[0..0] of TSafeArrayBound;
> I1,V1, V2, V3: SmallInt;
> P1, P2: PSmallInt;
> P3: Pointer;
> Succeed: THandle;
> Str1: String;
> Vr1: Variant;
> begin
> // Creating array
> rgsa[0].cElements:= 5;
> rgsa[0].lLbound:=0;
> PS1:= SafeArrayCreate(VT_I2,1,rgsa);
>
> //Writing to array
> V1:= 110;
> P1:= @[EMAIL PROTECTED]
> Succeed:= SafeArrayPutElement(PS1,[0,1],P1);
That's not right. The last parameter should be V1, not P1.
The last parameter is an untyped const in the Delphi declaration, which
means that you should pass the actual *value* you want stored in the
array. MSDN says to pass a pointer to the value, but the compiler takes
care of that detail for you.
As it is, you've give a four-byte value (the pointer P1) and the OS
stores it into space reserved for a two-byte value.
Also, the function returns an HResult, not a THandle, so change the
declaration of Succeed. And then check the return value before
proceeding with the rest of the code.
> //Reading from array
> Succeed:= SafeArrayGetElement(PS1,[0,1],P3);
That's not right, either. Just like before, you should pass the actual
variable you want to receive the SmallInt value from the array. In this
case, that's V3. MSDN says to pass a pointer, but the Delphi declaration
is an untyped var parameter, so the compiler takes care of the pointer
stuff for you.
Also, why are you passing an array of two indices for the second
parameter? It's only a one-dimensional array.
> P2:=PSmallInt(P3);
> VR1:= P2^; // It seems this line has no effect but it's not.
> V3:= P2^;
> Label3.Caption:= IntToStr(V3);
>
> In this case I don't have any problem and the value of V3 is 110, but
> when I omit the " VR1:= P2^;", a line that seems has no effect, the
> value of V3 will corrupt.
> What is the resone???
Well, you were calling the functions wrong, so it's nor surprising that
you didn't get the expected results. And since part of what you were
doing wrong involved reading and writing memory that wasn't supposed to
be accessed, it's no surprise that other seemingly unrelated code
changed the behavior of your program.
--
Rob


|