Overloading the assignment operator for Object Pascal - pascal

What happens when the assign operator := gets overloaded in Object Pascal? I mainly mean what gets evaluated first and more importantly how (if possible) can I change this order. Here is an example that bugs me:
I declare TMyClass thusly:
TMyClass = class
private
FSomeString: string;
class var FInstanceList: TList;
public
function isValid: boolean;
property SomeString: String write setSomeString;
end;
the isValid function checks MyObject for nil and dangling pointers.
Now lets assume I want to overload the := operator to assign a string to TMyClass. I also want to check if the object I'm assigning this string to is a valid object and if not create a new one, so:
operator :=(const anewString: string): TMyClass;
begin
if not(result.isValid) then
result:= TMyObject.Create;
result.SomeString:= aNewString;
end;
In short I was hoping that the result would automatically hold the pointer to the object I'm assigning to. But tests with the following:
procedure TForm1.TestButtonClick(Sender: TObject);
var
TestObject: TMyObject;
begin
TestObject:= TMyObject.Create;
TestObject:= 'SomeString';
TestObject.Free;
end;
led me to believe that instead an intermediate value for result is assigned first and the actual assignment to TestObject happens after the code in := executes.
Everything I know about coding is self taught but this example shows that I clearly missed some basic concept somewhere.
I understand that there are easier ways to do this than by overloading a := operator but out of scientific curiosity is there ANY way to make this code work? (No matter how complicated.)

It's not possible to do what you want with operator overloads. You must use a method.
The problem is that the := operator does not give you the access to the left hand side (LHS) argument (here it's the Self, a pointer to the current instance) but only to the right hand side argument.
Currently in you example if not(result.isValid) then is dangereous because the result at the beginning of the function is undefined (it can have any value, it can be either nil or not and when not nil, calling isValid will lead to some possible violation access. It does not represent the LHS at all.
Using a regular method you would have an access to the Self and you could call isValid.

I do not have Lazarus to check, but it is possible in Delphi in the following way. We give access to an instance of the class indirectly via TValue.
Here is a sample class:
type
TMyClass = class(TComponent)
private
FSomeString: string;
published
property SomeString: string read FSomeString write FSomeString;
end;
And we do the following in the container class (for example, TForm1).
TForm1 = class(TForm)
private
FMyClass: TMyClass;
function GetMyTypeString: TValue;
procedure SetMyTypeString(const Value: TValue);
public
property MyClass: TValue read GetMyTypeString write SetMyTypeString;
end;
...
function TForm1.GetMyTypeString: TValue;
begin
Result := FMyClass;
end;
procedure TForm1.SetMyTypeString(const Value: TValue);
begin
if Value.Kind in [TTypeKind.tkChar, TTypeKind.tkUString,
TTypeKind.tkString, TTypeKind.tkWChar, TTypeKind.tkWString]
then
begin
if not Assigned(FMyClass) then
FMyClass := TMyClass.Create(self);
FMyClass.SomeString := Value.AsString;
end else
if Value.Kind = TTypeKind.tkClass then
FMyClass := Value.AsType<TMyClass>;
end;
In this case both button clicks will work properly. In other words, it simulates := overloading:
procedure TForm1.Button1Click(Sender: TObject);
begin
MyClass := 'asd';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MyClass := TMyClass.Create(self);
end;
And here is how to get access to TMyClass instance:
procedure TForm1.Button3Click(Sender: TObject);
begin
if Assigned(TMyClass(MyClass.AsObject)) then
ShowMessage(TMyClass(MyClass.AsObject).SomeString)
else
ShowMessage('nil');
end;

Related

Why does setting a Char variable to nil cause compilation to fail?

In my case below I don't want c to be assigned to anything until the first character of the file is read.
I tried setting the Char variable c to nil (c := nil;) but compilation fails. I tried an empty string like below, and still doesn't work.
It works when I set it to an empty space, but it seems peculiar that I have to do that.
Is there any way to initialize a Char to a null like value as you can do in other languages?
program CSVToMarkdown;
{$mode objfpc}{$H+}{$J-}
uses
Sysutils;
var
f: File of Char;
c: Char;
begin
Assign(f, 'test.csv');
Reset(f);
c := '';
while not Eof(f) do
begin
Read(f, c);
Write(c);
end;
Close(f);
ReadLn;
end.
NIL is a value for pointers, or reference types (interfaces,class, dyn arrays) in general.
Non reference types don't have a NIL value, the type char can take values from #0 to #255, and all are valid, though sometimes when interfacing to other languages #0 is interpreted as end of string.
If you mean nullable types like in Java or .NET, there is no default support for them as they have the disadvantage of the type becoming larger than need be (iow becoming a pseudo record with added NULL boolean).
There are some generics based solutions that try to implement nullable types, but I haven't used them, and they are not part of the standard distribution.

Why SIGSEGV Exception here [duplicate]

This question already has answers here:
Delphi: Access Violation at the end of Create() constructor
(2 answers)
Closed 3 years ago.
I am trying following code to create a simple GUI application:
program RnTFormclass;
{$mode objfpc}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Interfaces, Forms, StdCtrls;
type
RnTForm = class(TForm)
private
wnd: TForm;
btn: TButton;
public
constructor create;
procedure showit;
end;
constructor RnTForm.create;
begin
Application.Initialize;
wnd := TForm.Create(Application);
with wnd do begin
Height := 300;
Width := 400;
Position:= poDesktopCenter;
Caption := 'LAZARUS WND';
end;
btn := TButton.Create(wnd);
with btn do begin
SetBounds(0, 0, 100, 50);
Caption := 'Click Me';
Parent := wnd;
end;
end;
procedure RnTForm.showit;
begin
wnd.ShowModal; {Error at this line: Throws exception External: SIGSEGV }
end;
var
myform1: RnTForm;
begin
myform1.create;
myform1.showit;
end.
However, it is throwing exception as mentioned as a comment in code above. Where is the problem and how can it be solved?
myform1.Create should be myform1 := RnTForm.Create.
In your code above, myform1 is a nil pointer (since it is a global variable, it is initialized to nil) until you assign something to it, in this case a (pointer to a) new instance of a RnTForm.
And of course, if myform1 is a nil pointer, you cannot use it as if it was indeed pointing to an object (so myform1.showit will not work).

How to proceed when passing a Record vs Passing a class to a procedure

Lets say i have a class called TProgramSettings which looks like this:
TProgramSettings = class
flags: UInt32;
...
end;
PProgramSettings = ^TProgramSettings;
So I initialize my program like this:
var
MyProgramSettings: TProgramSettings;
begin
MyProgramSettings := TProgramSettings.Create;
MyProgramSettings.Flags := 0;
ApplySettings(#MyProgramSettings);
And the procedure ApplySettings looks like this:
procedure ApplySettings(ProgramSettings: PProgramSettings);
var
MyObject : TCustomObject;
begin
MyObject := TCustomObject.Create;
MyObject.Settings.Flags := ProgramSettings^.Flags;
...
end;
Right now my code looks like this, however I wonder if there is any better way to do it? Am I breaking Object Pascal/Delphi code conventions? Would it be better to just make TProgramSettings a record? I really dont understand the difference between Records and Classes, all I know is that classes must be initialized. In the case I make TProgramSettings a record from what I've read I shouldn't pass a pointer to it since the record points to the same addres in memory and doesn't need to be referenced like the class. How should I go about it? Any help would be aprreciated :)
An object of type class is already a pointer, so there really is no need to dereference it as you do. The equivalent is
TProgramSettings = class
flags: UInt32;
...
end;
…
var
MyProgramSettings: TProgramSettings;
begin
MyProgramSettings := TProgramSettings.Create;
MyProgramSettings.Flags := 0;
ApplySettings(MyProgramSettings);
…
procedure ApplySettings(ProgramSettings: TProgramSettings);
var
MyObject : TCustomObject;
begin
MyObject := TCustomObject.Create;
MyObject.Settings.Flags := ProgramSettings.Flags;
...
end;
As regards the difference between a record and a class object, well, one way to think of it is that when you define a record as a var, that definition creates the record (no need to call 'Create') whereas for a class you are just creating a point to the object, and you still need to create the object itself. There is a lot more to than that, but it is away to start thinking about it.

Delphi: Sending multiple strings through sockets?

I am currently using delphi 6 (yes, I know.. but its so far getting the job done.)
I am using Serversocket, and client socket. When I have my client connect to my server, I would like to have it send some info, like computername, lAN IP, OS name, ping.
At the moment I only have the client sending the computer name to the server, I am wondering how can I send multiple information, and set it up accordingly in my grid? here is the source code:
Client:
unit client1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp;
type
TForm1 = class(TForm)
Client1: TClientSocket;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Client1Connect(Sender: TObject; Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function Getusernamefromwindows: string;
var
iLen: Cardinal;
begin
iLen := 256;
Result := StringOfChar(#0, iLen);
GetUserName(PChar(Result), iLen);
SetLength(Result, iLen);
end;
function Getcomputernamefromwindows: string;
var
iLen: Cardinal;
begin
iLen := MAX_COMPUTERNAME_LENGTH + 1;
Result := StringOfChar(#0, iLen);
GetComputerName(PChar(Result), iLen);
SetLength(Result, iLen);
end;
function osver: string;
begin
result := 'Unknown';
case Win32MajorVersion of
4:
case Win32MinorVersion of
0: result := 'windows 95';
10: result := 'Windows 98';
90: result := 'Windows ME';
end;
5:
case Win32MinorVersion of
0: result := 'windows 2000';
1: result := 'Windows XP';
end;
6:
case Win32MinorVersion of
0: result := 'Windows Vista';
1: result := 'Windows 7';
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Client1.Host := '192.168.1.106';
Client1.Active := true;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Client1.Active := false;
end;
procedure TForm1.Client1Connect(Sender: TObject; Socket: TCustomWinSocket);
begin
Client1.Socket.SendText(Getcomputernamefromwindows + '/' + Getusernamefromwindows);
(*Upon connection to server, I would like it send the os name, but as you
can see I already have SendText being used*)
end;
end.
Server:
unit server1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ScktComp, Grids, DBGrids;
type
TForm1 = class(TForm)
Server1: TServerSocket;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
StringGrid1: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure Server1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
With StringGrid1 do begin
Cells[0,0] := 'Username';
Cells[1,0] := 'IP Address';
Cells[2,0] := 'Operating System';
Cells[3,0] := 'Ping';
end;
end;
(* cells [0,0][1,0][2,0][3,0]
are not to be changed for
these are used to put the
titles in
*)
procedure TForm1.Server1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
var
begin
with StringGrid1 do begin
Cells[0,1] := Socket.ReceiveText;
Cells[1,1] := Server1.Socket.Connections[0].RemoteAddress;
(*in this area I want it to receive the os version info and place it in
Cells[2,1]*)
end;
end;
end.
You already know the answer, because you are already doing it. Send the various strings with delimiters in between them (in your example, you are using /, but you could also use CRLFs, string length prefixes, etc), and then some final delimiter to signal the end of the data.
The real problem with your code is the use of SendText() and ReceiveText(). SendText() is not guaranteed to send the entire string in one go. It returns how many bytes it actually sent. If fewer than your string length, you have to call SendText() again to send the remaining bytes. As for ReceiveText(), it just returns whatever arbitrary data is on the socket at that moment, which may be an incomplete string, or multiple strings merged together.
You are using lower-level I/O methods without first designing a higher level protocol to describe the data being sent. You need a protocol. Design how you want your data to look, then format your data that way and use the methods to send/receive that data, then break apart the data as needed when received.
So, in this case, you could send a single CRLF-delimited string that contains /-delimited values. The server would then read until it reaches the CRLF, then split the line and use the values according.

ResourceString VS Const for string literals

I have a couple of thousands string literals in a Delphi application. They have been isolated in a separate file and used for localization in the past.
Now I don't need localization any more.
Is there any performance penalty in using resourcestring compared to plain constants.
Should I change those to CONST instead?
The const string makes a call to _UStrLAsg and the resource string ends up in LoadResString.
Since the question is about speed there is nothing like doing a test.
resourcestring
str2 = 'str2';
const
str1 = 'str1';
function ConstStr1: string;
begin
result := str1;
end;
function ReceStr1: string;
begin
result := str2;
end;
function ConstStr2: string;
begin
result := str1;
end;
function ReceStr2: string;
begin
result := str2;
end;
procedure Test;
var
s1, s2, s3, s4: string;
begin
s1 := ConstStr1;
s2 := ReceStr1;
s3 := ConstStr2;
s4 := ReceStr2;
end;
For the first time I used AQTime added in DelphiXE to profile this code and here is the result. The time column show Machine Cycles.
I might have done a lot of rookie mistakes profiling this but as I see it there is a difference between const and resourcestring. If the difference is noticeable for a user depends on what you do with the string. In a loop with many iterations it can matter but used to display information to the users, not so much.
Since they are stored in a single file which presumably does little else (well done!), there's no reason not to try it out. I predict it won't make any discernible difference to performance, but I guess it depends on what else you are doing in your app.
Resource strings do incur overhead.
Compared to displaying such a string, or writing it to a file or database, the overhead is not much.
On the other hand it is just a switch from the resourcestring to const keyword (and back if you ever consider to to localization again).

Resources