I'm writing an IDE for DWScript and have got it stepping through code using the debugger. I now wish to add a display of 'local variables' (i.e those in scope). Can someone give me a pointer to the means of doing this? I can get a list of all symbols but do not understand how to get the current scope part of things.
Thanks.
Cast the IdwsProgramExecution to TdwsProgramExecution, you'll gain access to a "CurrentProg", property, a TdwsProgram which is either a TdwsMainProgram (if you're in the main) or a TdwsProcedure (if you're in a proc/func/method). Those will have a Table property, which lists the local symbols, that's the most direct scope.
That Table will have one or more Parents, which refers the parent scopes (hierarchically, in terms of source code scope).
If in a TdwsProcedure, you may also want to look at its FuncSymbol property, which will have a table of parameters (useful if you want to directly isolate the parameters from the rest of the local scope)
For any others reading this question, I will show some supplementary info concerned with getting the value of a symbol. The symbol is found as described by Eric above but it is hard to work out how to get the actual value of the symbol. The code below is a procedure that populates a TMemo (memLocalVariables) with local variables each time it is called. There are some features missing like neat formatting of the variable value and access to calling parameters. I call this from the debugger 'dsDebugSuspended' state. The less intuitive bit is the access to the symbol data on the stack and the use of the stack base pointer. A great way to learn how the compiler works! But, maybe there is a utility function somewhere I've not found...? Eric?
procedure DrawLocalVariables;
var
ProgramExecution : TdwsProgramExecution;
I : integer;
Sym : TSymbol;
V : variant;
Adr : integer;
SymbolTable : TSymbolTable;
begin
memLocalVariables.Lines.Clear;
ProgramExecution := TdwsProgramExecution( dwsDebugger1.Execution );
SymbolTable := ProgramExecution.CurrentProg.Table;
For I := 0 to SymbolTable.Count-1 do
begin
Sym := SymbolTable[I];
if Sym is TDataSymbol then
begin
Adr := TDataSymbol( Sym).StackAddr + ProgramExecution.Stack.BasePointer;
ProgramExecution.Stack.ReadValue( Adr, V );
memLocalVariables.Lines.Add( Format( '%s = %s', [ Sym.Name, VarToStr(V) ] ));
end;
end;
end;
Related
Basically, I have an application which will retrieve information out of an INI file and part of this process includes extracting the names -stored in the INI- of some procedures declared at global scope inside another unit.
I use the following to get the SQL method:
MyIni.ReadString('SQL', SubStr + '_Insert, '');
SubStr is the type of data I want, for example "titles", this is prefixed with the type of SQL procedure I want, in this case "_Insert" therefore, my request here could be seen as:
MyIni.ReadString('SQL', 'titles_Insert', '');
This would then retrieve the appropriate SQL procedure name "InsertTitlesSql" which is displayed inside the INI thus:
[SQL]
titles_Insert=InsertTitlesSql
I have a unit which lists the SQL procedures we use.
Like so:
unit uSqlLibrary;
interface
function InsertTitlesSql: string;
implementation
function InsertTitlesSql: string;
begin
{
INSERT INTO TITLES (ENGLISH, AFRIKAANS, KEY)
VALUES (:english,
:afrikaans,
:key)
}
Result := ''
+'INSERT INTO TITLES (ENGLISH, AFRIKAANS, KEY) '
+'VALUES (:english, '
+' :afrikaans, '
+' :key) ';
end;
end.
I've tried TGenericContainer without any success, I've also tried MethodAddress but I don't know how to tell MethodAddress to look at the other unit without an Object to reference (Form1.MethodAddress() for example) my best result so far is this:
type
TExec = procedure of object;
procedure TForm1.Button1Click(Sender: TObject);
var
M : TMethod ;
E : TExec ;
begin
M.Code := #Test; // Where "Test" is a procedure inside a secondary Unit.
E := TExec(M);
E;
end;
What I'm trying to do is get the SQL procedure by name that I want ( function InsertTitlesSql : string;) and assign it to a generic method that behaves in the same way.
My team lead has said that he doesn't want to edit the uSqlLibrary; so I can't do it that way and have thought to go by the method's name instead. Any other suggestions are welcome.
Hope this is clear. Sorry if it's not ( my use of terminology is not so good xD ). I'll try to elaborate on your queries to the best of my knowledge if I can.
You cannot use RTTI to enumerate procedures with global scope. You can enumerate methods, so you could convert your global procedures to be static class methods.
However, you also state that your team lead does not want you to change uSqlLibrary. This seems a little short sighted in my opinion. Feel free to tell him/her that I said so.
Anyway, if you cannot change uSqlLibrary then you cannot use RTTI. So you'll need to construct your own lookup table. Use a generic dictionary:
uses
System.Generics.Collections;
var
ProcTable: TDictionary<string, TProc>;
Instantiate it in the usual way. Add your functions at program startup:
....
ProcTable.Add('InsertTitlesSql', InsertTitlesSql);
....
When you need to look one up and call it do this:
var
Proc: TProc;
....
if not ProcTable.TryGetValue(ProcName, Proc) then
raise EProcNotFound.CreateFmt(...);
Proc();
The default equality comparer used for the key is case-sensitive by default. So you may elect to supply a custom equality comparer that compares keys without case sensitivity.
I need store a variant value (which always return a string) in a PChar variable now i'm using this code
procedure VariantToPChar(v:variant; p : PChar);
Var
s : String;
begin
s:=v;
GetMem(p,Length(s)*Sizeof(Char));
StrCopy(p, PChar(s));
end;
But i'm wondering if exist a better way
Do you really, really have to create a PChar? As long as possible i would use Strings, and only if an external library (like the Windows API) requires a PChar, i would cast it.
uses
Variants;
var
vText: Variant;
sText: String;
begin
vText := 'Hello world';
// VarToStr() can handle also null values
sText := VarToStr(vText);
// If absolutely necessary, cast it to PChar()
CallToExternalFunction(PChar(sText));
Doing it like this you can avoid problems with memory (de)allocation, null values, and Ansi/Unicode chars. If the external function wants to write into the string, you can use SetLength() before casting. Maybe the article Working with PChar could give you some ideas.
Update: You really shouldn't do this or use this code as you're likely to encourage people to write code that leaks. People will call this and fail to free the memory since they don't know that this function allocates memory.
If you want to store something in a PChar size buffer, and have that value still be associated with p (the pointer p is modified and is different when you return from the procedure), then you need to make the parameter a var (by-reference instead of by-value) parameter like this:
procedure AllocPCharBufFromVariant(v:variant; var p : PChar);
Var
s : String;
begin
try
s:=v;
GetMem(p,(Length(s)+1)*Sizeof(Char)); // fixed to add 1 for the nul
StrCopy(p, PChar(s));
except
on E:EVariantError do
begin
p := nil;
end;
end;
end;
I have also shown above handling EVariantError, which I have chosen to handle by returning nil in the p parameter, but you should think about how you want it to work, and then deal with it somehow.
The above code also leaks memory which is awful, so I renamed it AllocPChar. It seems like your original code has so many problems that I can't recommend a good way to do what looks like a giant pile of bad things and the name you chose is among the most awful choices.
At least the name Alloc gives me a hint so I'm thinking "I better free this when I'm done with it".
I suspect just a
PChar(string(v))
expression will do the trick.
And the memory used to store the converted string content will be available in the scope of this code (i.e. as long as the string(v) will be referenced - so you may want to use an explicit string variable to ensure that your PChar memory is still allocated).
In VirtualTreeview, I am storing my data in the PVirtualNodes. I have experienced several Access Violations (typically with "Read of adress 00000000") in my App, and they mostly (I'd actually dare to say Always) occur when I am doing something with my Node Data.
However, the thing is, I declare my stuff & use it like this:
// DUMMY CODE - Not written or tested in IDE
var
MyNode : PVirtualNode;
MyData : PMyNodeData;
Begin
MyNode := VST.GetFirstSelected;
if Assigned(MyNode) then
Begin
MyData := VST.GetNodeData(MyNode);
if Assigned(MyData) then
Begin
MyData.DummyProperty := 'Test';
End;
End;
End;
As you probably noticed, I do not "dereference" (correct?) my "MyData" by doing MyData^! The reason I don't is that I have been told it was not necessary to add the caret to the pointer name, however I have a feeling that it has something to do with it. If I knew, I wouldn't be posting on here. ;)
So my question is: Is it in the end necessary to add the little ^ to MyData? And is it possible that by not doing that, I may provoke an Access Violation?
When you have a pointer to a record, then you can omit the ^. The following are equivalent:
MyData.DummyProperty
MyData^.DummyProperty
This is also the case for the deprecated Turbo Pascal object. I would expect it to be so for Delphi classes, although I have never tried with them since they are already reference types.
Sadly, this is not the explanation for your AV.
Using ^ to dereference records is optionnal as it is assumed implicitly by the compiler. When not using any hard typecast, any situation that would requires the "^" would not compile. But only 1 level of dereferencing is implicit.
type
TMyRecord = record
MyField : Integer;
end;
PMyRecord = ^TMyRecord;
PPMyRecord = ^PMyRecord;
procedure DoSomething;
var vMyField : PPMyRecord;
begin
vMyField.MyField; <---Won't compile
vMyField^.MyField; <---Will compile
end;
As for your access violation, here's my best guess based on what you wrote... Assuming your exemple is representative (i.e. that is, crash on assigning a string), and assuming PMyNodeData points to a record. I'd guess that PMyNodeData's memory was reserved with "GetMem" instead of "New", making the string field of the record uninitialized.
There is an exception where Data.xx and Data^.xx are not the same: when the field pointed at is of the same pointer type or the generic pointer type:
var
x: PPointer;
y: Pointer;
begin
x := GetPPointer();
y := x;
y := x^;
end;
I consider it best practice to always add the operator ^ when the pointed value is used to avoid ambiguous situations like above.
Given your example: The problem is possibly memory corruption. Did you set NodeDataSize correctly?
I have a main app and a type library contains 2 COM objects, one is IFile, one is IFiles. IFiles creates IFile, and stores them in a TLIST, and has standard methods like Add, Remove etc. Both IFile and IFiles are TAutoObject.
"Add" method in IFiles is working fine, it simply creates IFile object [Code 1], and adds it to TList. Problem is IFile object instance gets lost in a very strange way. see [Code 2]
[Code 1]
function IFiles.Add(AFilename: String): IFile;
begin
Result := CoIFile.Create;
Result.Filename := AFilename;
// ShowMessage(IntToStr(Result._AddRef));
fFiles.Add(#Result);
end;
In the main app I have test code like this.
[Code 2]
var
i: Integer;
f: IFile;
Files: IFiles;
begin
Files := CoTIFile.Create;
for i:= 1 to 4 do
begin
// Create a dummy file object
f := Files.Add('Filename ' + IntToStr(i));
f._AddRef; // Not sure if AddRef works like this
// Prints out the last file
Memo1.Lines.Add(Files.Files[i-1].Filename);
end;
for i:= 0 to Files.Count-1 do
begin
f := Files.Files[i];
// F is nil at all time.
if (f<>nil) then Memo1.Lines.Add(f.Filename); // ! No print out.
end;
end;
From the 2nd loop, even though fFiles.Count = 4, but all contents have lost. Do I need some extra treatment in IFile to handle AddRef and Release? or the way IFiles.Add method I wrote is wrong?
Try using TInterfaceList rather than TList to store the instances of IFile. This may solve your problem.
The problem in your original code was that you were adding an IFile pointer to the list, but when you read a value out of the list later, you assigned the pointer directly to another IFile variable. So you had was was essentially a PIFile value stored in an IFile variable. Delphi generally allows you to assign the untyped Pointer type to any pointer-like type, including interfaces.
To fix your original code, you would need to write the second look something like this:
var
p: Pointer;
for i := 0 to Pred(Files.Count) do begin
p := Files.Files[i];
if not Assigned(p) then
continue;
f := IFile(p^);
if not Assigned(f) then
continue;
Memo1.Lines.Add(f.Filename);
end;
You were right to call f._AddRef in your first loop. When IFiles.Add returns, the reference count on the result is 1 because the value stored in the loop is a pointer, not the actual reference. You need to increment the reference count because f is going to be re-used for other values. Since the reference you're manually counting is stored in the FFiles list, it would be better to call _AddRef inside IFiles.Add instead of waiting until it returns.
When you clear the list, or as you remove items from the list, you would need to call _Release on all the interface references.
But Toby's answer gives the better idea: Use TInterfaceList to store a list of interfaces. TList simply isn't suited to the task by itself.
A final piece of advice: The "I" prefix on names is used to denote interface types. Interfaces don't have method implementations of their own. You've shown the implementation of IFiles.Add, so IFiles clearly isn't an interface type. It should be named TFiles instead, or maybe TFileList.
The COM objects i automaticly released if there is no references to it.
In Code 1 the COM object gets released at the "end" statement.
I think you need to creat a wrapper object, and that wrapper object is what you add to files.
In sory i don't have the time to creat an example right now.
TypeInfo(Type) returns the info about the specified type, is there any way to know the typeinfo of a var?
var
S: string;
Instance: IObjectType;
Obj: TDBGrid;
Info: PTypeInfo;
begin
Info:= TypeInfo(S);
Info:= TypeInfo(Instance);
Info:= TypeInfo(Obj);
end
This code returns:
[DCC Error] Unit1.pas(354): E2133 TYPEINFO standard function expects a type identifier
I know a non instantiated var is only a pointer address.
At compile time, the compiler parses and do the type safety check.
At run time, is there any way to know a little more about a var, only passing its address?
No.
First, there's no such thing as a "non-instantiated variable." You instantiate it by the mere act of typing its name and type into your source file.
Second, you already know all there is to know about a variable by looking at it in your source code. The variable ceases to exist once your program is compiled. After that, it's all just bits.
A pointer only has a type at compile time. At run time, everything that can be done to that address has already been determined. The compiler checks for that, as you already noted. Checking the type of a variable at run time is only useful in languages where a variable's type could change, as in dynamic languages. The closest Delphi comes to that is with its Variant type. The type of the variable is always Variant, but you can store many types of values in it. To find out what it holds, you can use the VarType function.
Any time you could want to use TypeInfo to get the type information of the type associated with a variable, you can also directly name the type you're interested in; if the variable is in scope, then you can go find its declaration and use the declared type in your call to TypeInfo.
If you want to pass an arbitrary address to a function and have that function discover the type information for itself, you're out of luck. You will instead need to pass the PTypeInfo value as an additional parameter. That's what all the built-in Delphi functions do. For example, when you call New on a pointer variable, the compiler inserts an additional parameter that holds the PTypeInfo value for the type you're allocating. When you call SetLength on a dynamic array, the compiler inserts a PTypeInfo value for the array type.
The answer that you gave suggests that you're looking for something other than what you asked for. Given your question, I thought you were looking for a hypothetical function that could satisfy this code:
var
S: string;
Instance: IObjectType;
Obj: TDBGrid;
Info: PTypeInfo;
begin
Info:= GetVariableTypeInfo(#S);
Assert(Info = TypeInfo(string));
Info:= GetVariableTypeInfo(#Instance);
Assert(Info = TypeInfo(IObjectType));
Info:= GetVariableTypeInfo(#Obj);
Assert(Info = TypeInfo(TDBGrid));
end;
Let's use the IsClass and IsObject functions from the JCL to build that function:
function GetVariableTypeInfo(pvar: Pointer): PTypeInfo;
begin
if not Assigned(pvar) then
Result := nil
else if IsClass(PPointer(pvar)^) then
Result := PClass(pvar).ClassInfo
else if IsObject(PPointer(pvar)^) then
Result := PObject(pvar).ClassInfo
else
raise EUnknownResult.Create;
end;
It obviously won't work for S or Instance above, but let's see what happens with Obj:
Info := GetVariableTypeInfo(#Obj);
That should give an access violation. Obj has no value, so IsClass and IsObject both will be reading an unspecified memory address, probably not one that belongs to your process. You asked for a routine that would use a variable's address as its input, but the mere address isn't enough.
Now let's take a closer look at how IsClass and IsObject really behave. Those functions take an arbitrary value and check whether the value looks like it might be a value of the given kind, either object (instance) or class. Use it like this:
// This code will yield no assertion failures.
var
p: Pointer;
o: TObject;
a: array of Integer;
begin
p := TDBGrid;
Assert(IsClass(p));
p := TForm.Create(nil);
Assert(IsObject(p));
// So far, so good. Works just as expected.
// Now things get interesting:
Pointer(a) := p;
Assert(IsObject(a));
Pointer(a) := nil;
// A dynamic array is an object? Hmm.
o := nil;
try
IsObject(o);
Assert(False);
except
on e: TObject do
Assert(e is EAccessViolation);
end;
// The variable is clearly a TObject, but since it
// doesn't hold a reference to an object, IsObject
// can't check whether its class field looks like
// a valid class reference.
end;
Notice that the functions tell you nothing about the variables, only about the values they hold. I wouldn't really consider those functions, then, to answer the question of how to get type information about a variable.
Furthermore, you said that all you know about the variable is its address. The functions you found do not take the address of a variable. They take the value of a variable. Here's a demonstration:
var
c: TClass;
begin
c := TDBGrid;
Assert(IsClass(c));
Assert(not IsClass(#c)); // Address of variable
Assert(IsObject(#c)); // Address of variable is an object?
end;
You might object to how I'm abusing these functions by passing what's obviously garbage into them. But I think that's the only way it makes sense to talk about this topic. If you know you'll never have garbage values, then you don't need the function you're asking for anyway because you already know enough about your program to use real types for your variables.
Overall, you're asking the wrong question. Instead of asking how you determine the type of a variable or the type of a value in memory, you should be asking how you got yourself into the position where you don't already know the types of your variables and your data.
With generics, it is now possible to get the type info without specifying it.
Certain users indicated the following code doesn't compile without errors.
As of Delphi 10 Seattle, version 23.0.20618.2753, it compiles without errors, as seen below in the screenshot.
program TypeInfos;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.TypInfo;
type
TTypeInfo = class
class procedure ShowTypeInfo<T>(const X: T);
end;
{ TTypeInfo }
class procedure TTypeInfo.ShowTypeInfo<T>(const X: T);
var
LTypeInfo: PTypeInfo;
begin
LTypeInfo := TypeInfo(T);
WriteLn(LTypeInfo.Name);
end;
var
L: Exception;
B: Boolean;
begin
// Console output
TTypeInfo.ShowTypeInfo(L); // Exception
TTypeInfo.ShowTypeInfo(B); // Boolean
end.
Not that I know of. You can get RTTI (Run Time Type Information) on published properties of a class, but not for "normal" variables like strings and integers and so forth. The information is simply not there.
Besides, the only way you could pass a var without passing a type is to use either a generic TObject parameter, a generic type (D2008, as in ), or as an untyped parameter. I can't think of another way of passing it that would even compile.