OLE automation: How to check if a variant references an automation object - delphi

I would like to know how can i determine, whether a variant is referencing an OLE automation object, or not.
I'm exporting some Excel graphs to Powerpoint.
I have this code:
var PptFile: Variant;
....
// PptFile _might_ be initialized:
PptFile:=pptApp.Presentations.Open(pptFilename);
// It depends on whether the export has items which need to be exported to
// Powerpoint or not
....
// I would like to determine if PptFile does reference an OLE automated object or not
PptFile.SaveAs(excelFileName+'.pptx');
I know, it could be done by placing the last line of the code (with saveAs) between try...except...end, but i don't feel that approach is good enough.
I was reading about VarIsEmpty, VarIsEmptyParam, Nothing, this question, but i'm not sure about this.

You should use VarIsClear for this test.
Indicates whether the specified variant has an undefined value.
VarIsClear returns true if the given variant's value is undefined. The
value can be undefined for any of several reasons:
The Variant may have had its value set to Unassigned.
The Variant's value may be an interface type that has been set to nil (Delphi) or NULL (C++).
The Variant may be a custom variant that returns true from its IsClear method.
In all other cases, the function result is false.
Note: Do not confuse an unassigned variant with a Null variant. A Null variant is still assigned, but has the value Null. Unlike
unassigned variants, Null variants can be used in expressions and can
be converted to other types of variants.
However, I question whether or not it is needed. How could it be that PptFile was not assigned? That can only happen if the call to pptApp.Presentations.Open() fails, and that would raise an exception. Or am I mis-understanding this? I cannot at the present see any scenario in which you could reach the call to PptFile.SaveAs() for which PptFile had not been assigned.

Related

Scope of System.Variants.NullStrictConvert

In a VCL application tt avoid
Could not convert variant of type (Null) into type (OleStr)
errors and because i want that Null variants
to be automatically converted to empty strings, 0 integers, or false
booleans
(as specified in one of the answers to this question)
i set
uses System.Variants
//[...]
NullStrictConvert := False;
Is it ok to do this in the OnCreate method of the main datamodule of a VCL app? Is this setting global? I can't find this info in the official documentation.
From testing it seems that setting it once it is enough, but i'd like to have an extra reference.
This variable is defined at module scope and so has global impact. If you modify the variable, then all code in your module that executes subsequently will be affected.
The intention would be that you set the value once at module initialization and then leave it unchanged. Yes you can do that in a data module OnCreate, but personally I would make the change in a unit initialization block.

Why does Assigned return true for uninitialized variables?

I read many posts on forum about pointers, Assigned function, Free function, FreeAndNil function, etc... I already know Free function don't remove the pointer reference to an object assigned and FreeAndNil does it... All posts I read treat this subject considering Create method already was executed, or in other words, considering an object already created.
My question is: Why Assigned function returns true for a uninitialized object variable ?
Follow an example:
procedure TForm1.FormCreate(Sender: TObject);
var
Qry: TADOQuery;
begin
if Assigned(Qry) then
ShowMessage('Assigned')
else
ShowMessage('Unassigned');
Qry := TADOQuery.Create(nil);
if Assigned(Qry) then
ShowMessage('Assigned')
else
ShowMessage('Unassigned');
end;
That example displays 'Assigned' twice!
Conclusion: Immediately after Qry has been declared and before its create method has been executed the pointer to Qry isn't NIL !
If I put Qry := nil; at the first line into procedure above everything works fine... it displays 'Unassigned' and 'Assigned'.
Why??
Is there any safe way to know if a class variable already has its create method executed?
Your variable is a local variable and so is not initialized. It could contain any value.
The documentation says:
On the Win32 platform, the contents of
a local variable are undefined until a value is assigned to
them.
Note that, as an implementation detail, some types are managed and even local variables of managed types are initialized. Examples of managed types include: strings, interfaces, dynamic arrays, anonymous types and variants.
You ask:
Is there any safe way to know if a class variable already has its create method executed?
If that variable is a local variable, the answer is no. The onus falls to you the programmer. In practice it is seldom an issue because good code has short procedures which makes it harder for you to slip up. And even if you do the compiler will invariably warn you.
Other types of variables like class fields and global variables are initialized.
Because when creating a pointer, it cames with whatever garbage value was in that memory position. If you want to write NIL in it, it takes some CPU cycles, and I think it's not automatically done by Delphi because you may want something faster. In your example, why assign NIL to a variable, if soon afterwards you're going to put another value in it?
From the documentation of the Assigned function (emphasis mine):
Use Assigned to determine whether the pointer or procedure referenced by P is nil. P must be a variable reference of a pointer or procedural type. Assigned(P) corresponds to the test P<> nil for a pointer variable, and #P <> nil for a procedural variable.
Assigned returns false if P is nil, true otherwise.
Note: Assigned can't detect a dangling pointer--that is, one that isn't nil but no longer points to valid data. For example, in the code example for Assigned, Assigned won't detect the fact that P isn't valid.
The Assigned function is effectively implemented as:
function Assigned(const P): Boolean;
begin
Result := Pointer(P) <> nil;
end;
So the function isn't really checking whether the value truly is assigned. Rather it's checking a side-effect of being assigned.
As a result the function is guaranteed to return True if it is assigned.
But behaviour is undefined if the value is uninitialised. Basically since an uninitialised value has a garbage value left over from previous operations, it might be nil, or if might not.
Another thing to note is that Assigned has no way to determine the validity of its value. E.g. The following call to Assigned returns True even though the underlying object is no longer valid.
var
LObject: TObject;
begin
LObject := TObject.Create;
LObject.Free;
if Assigned(LObject) then ShowMessage('Still assigned!?');
end;
EDIT: Addendum
In response to the second part of your question.
Is there any safe way to know if a class variable already has its create method executed?
There is no safe way to determine if an object instance has been created. (There's also no way to reliably confirm that it hasn't already been destroyed.)
However, there are conventions (and good practices) you can follow to help you on the way.
First note that you should only be "unsure" if something was created if it's a deliberate feature of that piece of code. E.g. If you intend an object to be "lazy initialised".
What I'm trying to say here is: Never check Assigned just because you're worried that there might be a bug that prevents it from being assigned.
Not only is this impossible to do reliably, but you overcomplicate your code... Which increases the chance of bugs.
Also if you find something is unexpectedly not Assigned, then what can you do about it? Ignoring it would simply be pointless. Also, it's no good saying: "Ok, then I'll create the object". Because then you're duplicating creation logic in multiple places.
Basically you should try to make every part of your program correct - not have your program try to double-check itself everywhere.
So now that we're (hopefully) agreed that you only check if something is created if you've deliberately chosen that being created is optional. You do this as follows:
At first opportunity, ensure the variable/field reference is initialised to nil. So then it's guranteed to be assigned a value which means the object is not created. (Yes, the naming is a bit warped.)
You can set the vairable/field reference to a new instance of an object or set it by copying another reference of an already existing object. (Note the existing refernce might also be nil, but that doesn't cause any problems.)
If you ever destroy the object (or even just want to stop using it from that reference), set your variable/field reference to nil again.
NOTE: Delphi already initialises the member fields of a new class. So those won't need special attention.

How can I get the underlying raw Variant value of a Delphi 6 indexed property that accesses that Variant?

I have a Delphi 6 class object that contains an array of 30 Variants, each of which is exposed via a different indexed property. For example:
property responseCode: integer
Index 7 read getIndexedProperty_integer write setIndexedProperty_integer;
I did this to make using the array of Variants easier (helps the IDE's auto-complete) and to provide type safety. It works fine but now I have a wrinkle. The array of Variants are initialized to NULL when the class that wraps it is constructed, so I can tell if a particular variant has ever been instantiated with a value. A consequence of this is if only some of the Variants are instantiated (given valid values), any attempt to access a property that currently represents a NULL Variant will cause a Variant conversion error when Delphi tries to convert the variant to the type declared by the indexed property.
I would much rather not declare an "isValid" property for each indexed property. I was wondering if there was a way to use the TypeInfo library to get the raw value of the underlying Variant without having to access the indexed property directly and thus triggering the conversion Exception. Then I could write code like (using the example property above):
isValidProperty(responseCode);
and that function would return TRUE if the Variant underlying the responseCode property is not NULL and FALSE if it is.
I know I can walk the PPropList property list for the class and access the properties by name, but then I would have to use code like:
isValidProperty('responseCode');
and pass the property name in string form instead of passing in the property directly like the first isValidProperty() above. Is there a way to do this?
So you want "to get the raw value of the underlying Variant without having to access the indexed property directly and thus triggering the conversion Exception". So long as you can access the underlying Variant itself, yes, you can. You will need to change the container class itself most likely.
From the Delphi XE2 help page on variant types:
The standard function VarType returns a variant's type code. The
varTypeMask constant is a bit mask used to extract the code from
VarType's return value, so that, for example,
VarType(V) and varTypeMask = varDouble
returns True if V contains a Double or an
array of Double. (The mask simply hides the first bit, which indicates
whether the variant holds an array.) The TVarData record type defined
in the System unit can be used to typecast variants and gain access to
their internal representation.
You should be able to use a combination of the methods and records mentioned here to find out anything you want about the internal data inside the variant, including if it's a NULL variant, as well as getting direct access to it.
(This system seems slightly dodgy design to me: it doesn't seem a very type safe implementation... see my comment above. I think a design based on the actual types of the values you are expecting might be safer. But, this will let you achieve your goal.)

What is the difference between the VarIsEmpty and VarIsEmptyParam functions

Working in Delphi7 just now, I noticed that not only a VarIsEmpty function exists, but also a VarIsEmptyParam.
Since the help of Delphi does not give much explanation:
VarIsEmptyParam returns true if the given variant represents an unassigned
optional parameter.
If the variant contains any other value, the function result is false.
I was just wondering if anyone has used this function, and if so, how this function is meant to be used.
In COM it is possible to have optional parameters in a method call at any position, while in Delphi this is only possible at the end. So if you want to omit the parameter you can write EmptyParam instead. EmptyParam is a global variable initialized with the correct values.
Now when you are implementing a COM interface you have to deal with these optional parameters, too. The way to find out these omitted parameters is VarIsEmptyParam.
Note that even an empty variant given as a parameter yields VarIsEmptyParam = false, because the param is not omitted. It is just empty, but it is there.
So normally there is:
VarIsEmpty(v) ==> not VarIsEmptyParam(v)
and
VarIsEmptyParam(v) ==> not VarIsEmpty(v)

Scope of anonymous methods

One nice thing about anonymous methods is that I can use variables that are local in the calling context. Is there any reason why this does not work for out-parameters and function results?
function ReturnTwoStrings (out Str1 : String) : String;
begin
ExecuteProcedure (procedure
begin
Str1 := 'First String';
Result := 'Second String';
end);
end;
Very artificial example of course, but I ran into some situations where this would have been useful.
When I try to compile this, the compiler complains that he "cannot capture symbols". Also, I got an internal error once when I tried to do this.
EDIT I just realized that it works for normal parameters like
... (List : TList)
Isn't that as problematic as the other cases? Who guarantees that the reference is still pointing to an alive object whenever the anonymous method is executed?
Var and out parameters and the Result variable cannot be captured because the safety of this operation cannot be statically verified. When the Result variable is of a managed type, such as a string or an interface, the storage is actually allocated by the caller and a reference to this storage is passed as an implicit parameter; in other words, the Result variable, depending on its type, is just like an out parameter.
The safety cannot be verified for the reason Jon mentioned. The closure created by an anonymous method can outlive the method activation where it was created, and can similarly outlive the activation of the method that called the method where it was created. Thus, any var or out parameters or Result variables captured could end up orphaned, and any writes to them from inside the closure in the future would corrupt the stack.
Of course, Delphi does not run in a managed environment, and it doesn't have the same safety restrictions as e.g. C#. The language could let you do what you want. However, it would result in hard to diagnose bugs in situations where it went wrong. The bad behaviour would manifest itself as local variables in a routine changing value with no visible proximate cause; it would be even worse if the method reference were called from another thread.
This would be fairly hard to debug. Even hardware memory breakpoints would be a relatively poor tool, as the stack is modified frequently. One would need to turn on the hardware memory breakpoints conditionally upon hitting another breakpoint (e.g. upon method entry). The Delphi debugger can do this, but I would hazard a guess that most people don't know about the technique.
Update: With respect to the additions to your question, the semantics of passing instance references by value is little different between methods that contain a closure (and capture the paramete0 and methods that don't contain a closure. Either method may retain a reference to the argument passed by value; methods not capturing the parameter may simply add the reference to a list, or store it in a private field.
The situation is different with parameters passed by reference because the expectations of the caller are different. A programmer doing this:
procedure GetSomeString(out s: string);
// ...
GetSomeString(s);
would be extremely surprised if GetSomeString were to keep a reference to the s variable passed in. On the other hand:
procedure AddObject(obj: TObject);
// ...
AddObject(TObject.Create);
It is not surprising that AddObject keeps a reference, since the very name implies that it's adding the parameter to some stateful store. Whether that stateful store is in the form of a closure or not is an implementation detail of the AddObject method.
The problem is that your Str1 variable is not "owned" by ReturnTwoStrings, so that your anonymous method cannot capture it.
The reason it cannot capture it, is that the compiler does not know the ultimate owner (somewhere in the call stack towards calling ReturnTwoStrings) so it cannot determine where to capture it from.
Edit: (Added after a comment of Smasher)
The core of anonymous methods is that they capture the variables (not their values).
Allen Bauer (CodeGear) explains a bit more about variable capturing in his blog.
There is a C# question about circumventing your problem as well.
The out parameter and return value are irrelevant after the function returns - how would you expect the anonymous method to behave if you captured it and executed it later? (In particular, if you use the anonymous method to create a delegate but never execute it, the out parameter and return value wouldn't be set by the time the function returned.)
Out parameters are particularly difficult - the variable that the out parameter aliases may not even exist by the time you later call the delegate. For example, suppose you were able to capture the out parameter and return the anonymous method, but the out parameter is a local variable in the calling function, and it's on the stack. If the calling method then returned after storing the delegate somewhere (or returning it) what would happen when the delegate was finally called? Where would it write to when the out parameter's value was set?
I'm putting this in a separate answer because your EDIT makes your question really different.
I'll probably extend this answer later as I'm in a bit of a hurry to get to a client.
Your edit indicates you need to rethink about value types, reference types and the effect of var, out, const and no parameter marking at all.
Let's do the value types thing first.
The values of value types live on the stack and have a copy-on-assignment behaviour.
(I'll try to include an example on that later).
When you have no parameter marking, the actual value passed to a method (procedure or function) will be copied to the local value of that parameter inside the method. So the method does not operate on the value passed to it, but on a copy.
When you have out, var or const, then no copy takes place: the method will refer to the actual value passed. For var, it will allow to to change that actual value, for const it will not allow that. For out, you won't be able to read the actual value, but still be able to write the actual value.
Values of reference types live on the heap, so for them it hardly matters if you have out, var, const or no parameter marking: when you change something, you change the value on the heap.
For reference types, you still get a copy when you have no parameter marking, but that is a copy of a reference that still points to the value on the heap.
This is where anonymous methods get complicated: they do a variable capture.
(Barry can probably explain this even better, but I'll give it a try)
In your edited case, the anonymous method will capture the local copy of the List. The anonymous method will work on that local copy, and from a compiler perspective everything is dandy.
However, the crux of your edit is the combination of 'it works for normal parameters' and 'who guarantees that the reference is still pointing to an alive object whenever the anonymous method is executed'.
That is always a problem with reference parameters, no matter if you use anonymous methods or not.
For instance this:
procedure TMyClass.AddObject(Value: TObject);
begin
FValue := Value;
end;
procedure TMyClass.DoSomething();
begin
ShowMessage(FValue.ToString());
end;
Who guarantees that when someone calls DoSomething, that the instance where FValue points to still exists?
The answer is that you must guarantee this yourself by not calling DoSomething when the instance to FValue has died.
The same holds for your edit: you should not call the anonymous method when the underlying instance has died.
This is one of the areas where reference counted or garbage collected solutions make life easier: there the instance will be kept alive until the last reference to it has gone away (which might cause instance to live longer than you originally anticipated!).
So, with your edit, your question actually changes from anonymous methods to the implications of using reference typed parameters and lifetime management in general.
Hopefully my answer helps you going in that area.
--jeroen

Resources