I've already found this answer on how to check the Indy version at run-time, and there are multiple different ways. However I'm looking how to use conditionals to check the Indy version at compile-time. There's a feature in newer versions of Indy, and I want my open-source project to use this feature if it's available. But I need to conditionally compile it.
I've found IdVers.inc, but this file only contains constants - no version conditionals.
More specifically, the TIdHTTP has a property HTTPOptions which has a new choice hoWantProtocolErrorContent. If this is available, I'd like to use it.
How can I conditionally use this option if it's available?
I think you can get the result you're wanting to achieve using the
{$if declared ...
construct. There is an example of its usage in SysInit.Pas in the rtl:
function GetTlsSize: Integer;
{$IF defined(POSIX) and defined(CPUX86) and (not defined(EXTERNALLINKER))}
asm
// Use assembler code not to include PIC base gain
MOV EAX, offset TlsLast
end;
{$ELSE}
begin
Result := NativeInt(#TlsLast);
{$IF DECLARED(TlsStart)}
Result := Result - NativeInt(#TlsStart);
{$ENDIF}
[...]
As well as the article I mentioned in a comment, $If Declared,
there is also this in the D2009 online help.
$if declared works with methods of classes, e.g.
procedure TMyClass.DoSomething;
begin
{$if declared(TMyClass.Added)} // Added being a procedure of TMyClass
Added;
{$endif}
end;
Related
I want to show a label on a form when FastMM4 is being used ('Uses' in the project file), so that I don't make the mistake of giving the executable to someone who doesn't have FastMM_FullDebugMode.dll installed.
I tried these, but they have are no effect:
{$ifdef FullDebugMode}
LblFastMM4.Visible := true;
{$endif}
{$ifdef EnableMemoryLeakReporting}
LblFastMM4.Visible := true;
{$endif}
How can I detect FastMM4 at runtime?
Note: I don't 'officially' distribute the app with FastMM4. This is just a reminder to myself when I want to give the alpha version to a non-technical user for a quick look. It's annoying if they then bump into the error.
Your {$ifdef}'s don't work because your own code is not including FastMM4Options.inc directly, so FastMM's conditionals are not defined in scope of your code. They are only defined in scope of FastMM's code. You can't test for conditionals that are {$define}'d in someone else's unit.
However, you can use {$If Declared(...)} to check for public symbols that are in scope from using another unit. In this case, the interface section of FastMM4.pas declares various symbols under certain conditions, for instance TRegisteredMemoryLeak when EnableMemoryLeakReporting is defined, DebugGetMem when FullDebugMode is defined, etc.
{$if declared(DebugGetMem)}
LblFastMM4.Visible := true;
{$endif}
{$if declared(TRegisteredMemoryLeak)}
LblFastMM4.Visible := true;
{$endif}
A lot of options can be configured for FastMM. In your case the option DoNotInstallIfDLLMissing can be of value. A nice application is available for setting options: https://jedqc.blogspot.com/2007/07/new-fastmm4-options-interface.html
try this:
LblFastMM4.Visible := InitializationCodeHasRun;
One can use either
System.IOUtils.TPath.DirectorySeparatorChar
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.IOUtils.TPath.DirectorySeparatorChar
OR
System.SysUtils.PathDelim
Are there any particular differences, benefits using one over another part from System.IOUtils.TPath is more object oriented interface?
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.SysUtils
System.SysUtils.PathDelim was introduced in Delphi 6 / Kylix 1, as a means to enable the writing of platform independent code. The introduction of Kylix, the original Delphi Linux compiler, meant that for the first time Delphi code executed on a *nix platform, as well as its original target of Windows.
System.IOUtils.TPath.DirectorySeparatorChar is part of the IOUtils unit that was introduced more recently to support the current wave of cross-platform tooling, which supports MacOS, iOS, Android and will soon encompass Linux once more.
Where you have a choice between System.SysUtils and System.IOUtils, you are generally expected to use the latter. The System.IOUtils is the cross-platform unit for file system support. That said, you commonly would not use DirectorySeparatorChar directly, but instead would use methods like System.IOUtils.TPath.Combine.
TPath.DirectorySeparatorChar is defined in System.IOUtils as
{$IFDEF MSWINDOWS}
FDirectorySeparatorChar := '\'; // DO NOT LOCALIZE;
// ...
{$ENDIF}
{$IFDEF POSIX}
FDirectorySeparatorChar := '/'; // DO NOT LOCALIZE;
// ...
{$ENDIF}
while PathDelim is defined in System.SysUtils as
PathDelim = {$IFDEF MSWINDOWS} '\'; {$ELSE} '/'; {$ENDIF}
While the conditionals are slightly different, they would only differ if neither or both of MSWINDOWS and POSIX were defined, which is not the case for any platform. And if there would be such a platform in the future, the declarations would surely be fixed accordingly.
TL;DR: There is no difference, you can use either based on your preference.
I am shareing a project with someone codeing in xe6, I am using xe2 version 16. I get this error
There is no overloaded version of 'write' that can be called with these arguments
at this code.
{$IF CompilerVersion >= 19}
// Modified code for Delphi XE5 & later
tcpConnection.IOHandler.Write(TheMsg, IndyTextEncoding.Default );
{$ELSE}
// Original XE2 code
tcpConnection.IOHandler.Write(TheMsg, TIdTextEncoding.Default);
{$IFEND}
I have also added idGlobal in the uses. Any other reason this would give error?
IndyTextEncoding() is a series of overloaded functions, all taking an input parameter, all returning an IIdTextEncoding interface:
function IndyTextEncoding(AType: IdTextEncodingType): IIdTextEncoding; overload;
function IndyTextEncoding(ACodepage: Word): IIdTextEncoding; overload;
function IndyTextEncoding(const ACharset: String): IIdTextEncoding; overload;
{$IFDEF DOTNET}
function IndyTextEncoding(AEncoding: System.Text.Encoding): IIdTextEncoding; overload;
{$ENDIF}
{$IFDEF HAS_TEncoding}
function IndyTextEncoding(AEncoding: TEncoding): IIdTextEncoding; overload;
{$ENDIF}
IIdTextEncoding does not have a Default property (or any other encoding type properties). IIdTextEncoding was introduced to break away from Embarcadero's TEncoding class and simplify Indy's memory management of codepage/charset handlers.
In earlier versions of Indy, the TIdTextEncoding.Default property represented the OS default encoding. The correct way to get the OS default encoding in the latest version of Indy is to use the IndyTextEncoding_OSDefault() function:
function IndyTextEncoding_OSDefault: IIdTextEncoding;
Or the IndyTextEncoding(IdTextEncodingType) function with encOSDefault as the input parameter.
{$IF CompilerVersion >= 19}
// Modified code for Delphi XE5 & later
tcpConnection.IOHandler.Write(TheMsg, IndyTextEncoding_OSDefault);
// or: tcpConnection.IOHandler.Write(TheMsg, IndyTextEncoding(encOSDefault));
{$ELSE}
// Original XE2 code
tcpConnection.IOHandler.Write(TheMsg, TIdTextEncoding.Default);
{$IFEND}
The IndyTextEncoding_Default() function, by comparison, returns an IIdTextEncoding that represents Indy's default encoding that is specified in the IdGlobal.GIdDefaultTextEncoding variable (7bit ASCII by default).
If you want to use something that works in both Indy versions without using an {$IFDEF}, use the deprecated IndyOSDefaultEncoding() function:
function IndyOSDefaultEncoding{$IFNDEF DOTNET}(const AOwnedByIndy: Boolean = True){$ENDIF}: IIdTextEncoding;
tcpConnection.IOHandler.Write(TheMsg, IndyOSDefaultEncoding);
That being said, note that the OS default encoding varies from one machine to another, and from one platform to another. You should not be using it as the byte encoding in communication protocols. Use a standardized encoding instead, such as UTF-8.
Lastly, if you are going to use {$IFDEF} or {$IF}, Indy has its own {$DEFINE} statements in IdCompilerDefines.inc, and global version constants in IdGlobal.pas, that you can use to detect Indy versions. You might consider using those instead of the CompilerVersion constant. If you were to ever upgrade Indy in XE2, for example, then your code would break. You should be checking for Indy versions, not Compiler/RTL versions, eg:
// Indy version constants were added in 10.5.9.4850
// TIdTextEncoding was replaced with IIdTextEncoding in 10.6.0.0
{$IF (gsIdVersionMajor > 10) OR ((gsIdVersionMajor = 10) AND (gsIdVersionMinor >= 6))}
tcpConnection.IOHandler.Write(TheMsg, IndyTextEncoding_OSDefault);
{$ELSE}
tcpConnection.IOHandler.Write(TheMsg, TIdTextEncoding.Default);
{$IFEND}
I'm trying to convert my current Delphi 7 Win32 code to Delphi XE5 Android with minimal changes, so that my project can be cross-compiled to Win32 from a range of Delphi versions and Android from XE5.
Starting from XE5 there are breaking changes in language aimed at future. One of such changes is zero-based strings.
In older versions with 1-based strings the following code was correct:
function StripColor(aText: string): string;
begin
for I := 1 to Length(aText) do
but now this is obviously not right. Suggested solution is to use:
for I := Low(aText) to High(aText) do
This way XE5 Win32 handles 1-based strings and XE5 Android handles 0-based strings right. However there's a problem - previous Delphi versions (e.g. XE2) output an error on such code:
E2198 Low cannot be applied to a long string
E2198 High cannot be applied to a long string
I have quite a lot of string manipulation code. My question is - how to modify and keep above code to be compileable in Delphi 7 Win32 and Delphi XE5 Android?
P.S. I know I can still disable ZEROBASEDSTRINGS define in XE5, but that is undesired solution since in XE6 this define will probably be gone and all strings will be forced to be 0-based.
If you want to support versions that use one based strings then don't define ZEROBASEDSTRINGS. That's the purpose of that conditional.
There's no indication that I am aware of that the conditional will be removed any time soon. It was introduced in XE3 and has survived two subsequent releases. If Embarcadero remove it, none of their Win32 customers will not upgrade and they will go bust. Embarcadero have a track record of maintaining compatibility. You can still use TP objects and short strings. Expect this conditional to live as long as the desktop compiler does.
In fact, all the evidence points towards the mobile compilers retaining support for one based string indexing. All the utility string functions like Pos use one based indices, and will continue to do so. If Embarcadero really are going to remove support for one based string indexing, they'll be removing Pos too. I don't believe that is likely any time soon.
Taking your question at face value though it is trivial to write functions that return the low and high indices of a string. You just use an IFDEF on the compiler version.
function StrLow(const S: string): Integer; inline;
begin
Result := {$IFDEF XE3UP}low(S){$ELSE}1{$ENDIF}
end;
function StrHigh(const S: string): Integer; inline;
begin
Result := {$IFDEF XE3UP}high(S){$ELSE}Length(S){$ENDIF}
end;
Update
As Remy points out, the above code is no good. That's because ZEROBASEDSTRINGS is local and what counts is its state at the place where such functions would be used. In fact it's just not possible to implement these functions in a meaningful way.
So, I believe that for code that needs to be compiled using legacy compilers, as well as the mobile compilers, you have little choice but to disable. ZEROBASEDSTRINGS.
All of the RTL's pre-existing functions (Pos(), Copy(), etc) are still (and will remain) 1-based for backwards compatibility. 0-based functionality is exposed via the new TStringHelper record helper that was introduced in XE3, which older code will not be using so nothing breaks.
The only real gotchas you have to watch out for are things like hard-coded indexes, such as your loop example. Unfortunately, without access to Low/High(String) in older Delphi versions, the only way to write such code in a portable way is to use IFDEFs, eg:
{$IFDEF CONDITIONALEXPRESSIONS}
{$IF CompilerVersion >= 24}
{$DEFINE XE3_OR_ABOVE}
{$IFEND}
{$ENDIF}
function StripColor(aText: string): string;
begin
for I := {$IFDEF XE3_OR_ABOVE}Low(aText){$ELSE}1{$ENDIF} to {$IFDEF XE3_OR_ABOVE}High(AText){$ELSE}Length(aText){$ENDIF} do
DoSomething(aText, I);
end;
Or:
{$IFDEF CONDITIONALEXPRESSIONS}
{$IF CompilerVersion >= 24}
{$DEFINE XE3_OR_ABOVE}
{$IFEND}
{$ENDIF}
function StripColor(aText: string): string;
begin
for I := 1 to Length(aText) do
begin
DoSomething(aText, I{$IFDEF XE3_OR_ABOVE}-(1-Low(AText)){$ENDIF});
end;
end;
Conditional Expressions were introduced in Delphi 6, so if you don't need to support version earlier than Delphi 7, and don't need to support other compilers like FreePascal, then you can omit the {$IFDEF CONDITIONALEXPRESSIONS} check.
This is rather a sum up of the two answers:
As pointed out by Remy Lebeau, ZEROBASEDSTRINGS is a per-block conditional. That means that the following code will not work as expected:
const
s: string = 'test';
function StringLow(const aString: string): Integer; inline; // <-- inline does not help
begin
{$IF CompilerVersion >= 24}
Result := Low(aString); // Delphi XE3 and up can use Low(s)
{$ELSE}
Result := 1; // Delphi XE2 and below can't use Low(s), but don't have ZEROBASEDSTRINGS either
{$ENDIF}
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
{$ZEROBASEDSTRINGS OFF}
Memo1.Lines.Add(Low(s).ToString); // 1
Memo1.Lines.Add(StringLow(s).ToString); // 1
{$ZEROBASEDSTRINGS ON}
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
{$ZEROBASEDSTRINGS ON}
Memo1.Lines.Add(Low(s).ToString); // 0
Memo1.Lines.Add(StringLow(s).ToString); // 1 <-- Expected to be 0
{$ZEROBASEDSTRINGS OFF}
end;
There are 2 possible solutions:
A. Every time there's string items access or iteration place an IFDEF around it, which is indeed a lot of clutter for the code, but will work properly irregardless of ZEROBASEDSTRINGS setting around it:
for I := {$IFDEF XE3UP}Low(aText){$ELSE}1{$ENDIF} to {$IFDEF XE3UP}High(aText){$ELSE}Length(aText){$ENDIF} do
B. Since the ZEROBASEDSTRINGS conditional is per-block it never gets spoiled by 3rd party code and if you don't change it in your code you are fine (above StringLow will work fine as long as the caller code has the same ZEROBASEDSTRINGS setting). Note that if target is mobile, you should not apply ZEROBASEDSTRINGS OFF globally in your code since RTL functions (e.g. TStringHelper) will return 0-based results because mobile RTL is compiled with ZEROBASEDSTRINGS ON.
On a side note - One might suggest to write an overloaded versions of Low/High for older versions of Delphi, but then Low(other type) (where type is array of something) stops working. It looks like since Low/High are not usual functions then can not be overloaded that simply.
TL;DR - Use custom StringLow and don't change ZEROBASEDSTRINGS in your code.
How about defining this as an inc file? Put additional ifdefs depending on what Delphi versions you want to support. Since this code is only for versions before the ZBS to make it possible to use Low and High on strings it will not run into the problem with the ZEROBASEDSTRINGS define only being local.
You can include this code locally (as nested routines) then which reduces the risk of colliding with System.Low and System.High.
{$IF CompilerVersion < 24}
function Low(const s: string): Integer; inline;
begin
Result := 1;
end;
function High(const s: string): Integer; inline;
begin
Result := Length(s);
end;
{$IFEND}
As LU RD told above Low and High functions for string were only introduced in XE3. So how can you use functions in earlier Delphi verions, that are missed? Just the same way as always do - if the function is missed - go and write it!
You should only activate those compatibility additions for Delphi beyond XE3 version, using conditional compilation. One way is described in other answers, using >= comparison. Another usual way would be reusing jedi.inc definitions file.
Then for earlier Delphi versions you would add your own implementations of those, like
function Low(const S: AnsiString): integer; overload;
Pay attention to the overload specifier - it is what would make the trick possible, don't forget it!
You would have to write 4 functions for Delphi 7 till 2007, covering combinations of Low/High fn name and AnsiString/WideString data type.
For Delphi 2009 till XE2 you would have to add two more functions for UnicodeString datatype.
And also mark those function inline for those Delphi versions, that support it (this is where jedi.inc comes handy again.
Hopefully you don't need supprot for UTF8String, but if you do - you know what to do about it now (if compiler would manage to tell it from AnsiString when overloading...)
Is there any efficient way to add type specific code for delphi generics ?
For example something like this:
function TGT<T>.GetSize(a: T): integer;
begin
{$IF TypeInfo(T)=TypeInfo(String)}
result := Length(A);
{$ELSE}
result := SizeOf(A);
{$IFEND}
end;
function TGT<T>.Compare(a,b: T): integer;
begin
{$IF TypeInfo(T)=TypeInfo(String)}
result := AnsiCompareText(a,b);
{$ELSE}
result := a-b;
{$IFEND}
end;
So i need to implement some parts of the code in different ways depending on type.
For example if i implement Sort routine i would like to use direct comparison of values of integer/double/etc types (it is more efficient than calling of interface methods like delphi's standard generic containers do) and function AnsiCompareText for String type.
There some examples how to do it, but all of them based on check like this:
if TypeInfo(T)=TypeInfo(String) then xxx else if TypeInfo(T)=TypeInfo(Integer) then xxx
Problem here is that Delphi will check it in run-time only, that is (again) not so efficient.
I would like to make compiler to do all checks in compile-time and use only code specific for selected type.
Well, you certainly cannot hope to do anything like that with conditional compilation. Remember that conditional compilation for generics are handled in the generic compilation phase rather than the instantiation phase. And so you cannot expect different instantiations to be compiled with different branches of your conditional statement.
And you certainly can never get the compiler to accept Length(a) where the type of a is parametrised, because there is no way to specify a constraint that would allow the use of Length.
The only option is a run-time check.