EzDevInfo.com

delphi interview questions

Top delphi frequently asked interview questions

How do I make my GUI behave well when Windows font scaling is greater than 100%

When choosing large font sizes in the Windows control panel (like 125%, or 150%) then there are problems in a VCL application, every time something has been set pixelwise.

Take the TStatusBar.Panel. I have set its width so that it contains exactly one label, now with big fonts the label "overflows". Same problem with other components.

Some new laptops from Dell ship already with 125% as default setting, so while in the past this problem was quite rare now it is really important.

What can be done to overcome this problem?


Source: (StackOverflow)

BcdDivide function behave differently in Delphi XE and XE2

FmtBcd.pas has been extensively revised rewritten in Delphi XE2. In one of my projects, I have a case that uses a division operation on two Bcd values, but the two versions yield different results. In the worst case, the Delphi XE2 may throw a Bcd overflow error.

Example: Running the following code in Delphi XE2 console apps:

var A, B, C, D: TBcd;
begin
  A := StrToBcd('1');
  B := StrToBcd('3');
  BcdDivide(A, B, C);
  WriteLn(BcdToStr(C));

  try
    BcdMultiply(C, C, D);
    WriteLn(BcdToStr(D));
  except
    on E: Exception do
      WriteLn(E.Message);
  end;

  ReadLn;
end.

Output of the above will be:

0.333333333333333333333333333333333333333333333333333333333333333
BCD overflow

The variable C contains a Bcd Value with 63 decimal places of specificity. Performing a second BcdMultiply operation on variable C will cause a Bcd overflow error.

However, to run the same code in Delphi XE yields the following result without any exception prompt:

0.3333333333
0.11111111108888888889

Could anyone please suggest a best-practice method for resolving this problem?


Source: (StackOverflow)

Advertisements

Delphi XE6 link C code in iOS

I've built an App on Android using Delphi XE6 that requires C code. However on iOS I cannot make it work. I suspect the problem is related to arm/thumb status, but I am not sure. There is no problem in either system to call the C code from Pascal. But if the C code calls back a Pascal procedure iOS generates a "bad system call (12)"

Here is the pascal code:

    function testarm(a,b:integer):integer; cdecl; external "testC.o";

    Procedure testC;
    Begin
      testarm(1,2);
    end;

    function BackToPascal(a,b:integer): integer; cdecl;
    Begin
      result := a+b;
    end;

    ......

    exports
      BackToPascal;

And here is the C code:

extern int BackToPascal(int a,int b);

extern int testarm(int a,int b)
{
   int i;
   i = BackToPascal(a,b);
   return i+1;
}

On android this is how I am compiling (It is working):

..."arm-linux-androideabi-gcc.exe" -c test.c -o test.o -O3 -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8

On ios:

xcrun -sdk iphoneos clang -c -arch armv7 test.c -O3 -mfpu=neon -mtune=cortex-a8 -marm -march=armv7-a -mfloat-abi=softfp

I suspect that my xcode settings are wrong but I cannot figure out why.

When i debug, the error comes when calling "testC" in testarm when calling BackToPascal ( on "bl 0x8b8390 Xgobj.BackToPascal (int, int)" ). On Android it works perfect however the "bl" does not call directly "BackToPascal", but the following code:

75A82D94 12C68FE2         add r12, pc, #18874368 ; 0x1200000
75A82D98 73CA8CE2         add r12, r12, #471040 ; 0x73000
75A82D9C 40F2BCE5         ldr pc, [r12, #576]! ; 0x240

Which get into BackToPascal


Source: (StackOverflow)

EProgrammerNotFound exception in Delphi?

In Delphi 2009, SysUtils.pas contains this in line 425:

EProgrammerNotFound = class(Exception);
  • Is this simply an easter egg or something serious?
  • When should this exception be raised?
  • Does it also exist in Delphi Prism and/or Free Pascal?

Q: Is this exception class still declared in Delphi (currently XE7)? A: Yes, and it is even documented!

Nonstandard way to indicate software faults.

You can use EProgrammerNotFound as an alternative to indicate software faults detected at run time.


Source: (StackOverflow)

Are delphi variables initialized with a value by default?

I'm new to Delphi, and I've been running some tests to see what object variables and stack variables are initialized to by default:

TInstanceVariables = class
  fBoolean: boolean; // always starts off as false
  fInteger: integer; // always starts off as zero
  fObject: TObject; // always starts off as nil
end;

This is the behaviour I'm used to from other languages, but I'm wondering if it's safe to rely on it in Delphi? For example, I'm wondering if it might depend on a compiler setting, or perhaps work differently on different machines. Is it normal to rely on default initialized values for objects, or do you explicitly set all instance variables in the constructor?

As for stack (procedure-level) variables, my tests are showing that unitialized booleans are true, unitialized integers are 2129993264, and uninialized objects are just invalid pointers (i.e. not nil). I'm guessing the norm is to always set procedure-level variables before accessing them?


Source: (StackOverflow)

Webview not displaying in MacOS using Delphi XE2

I have started to convert the Webview interfaces to be consumed in Delphi. I have managed to get the webkit library to load, and the interface methods that is called appears to work correctly, however, I cannot seem to display the Webview on the main form.

Below is my interfaces that is declared

  WebFrameClass = interface(NSObjectClass)
  ['{7BE750C8-DFEC-4870-851A-12DBCB0B78F6}']
  end;

  WebFrame = interface(NSObject)
  ['{BCFA04BE-41AB-4B78-89C0-3330F12C7695}']
    procedure loadRequest(request: NSURLRequest); cdecl;
  end;
  TWebFrame = class(TOCGenericImport<WebFrameClass, WebFrame>)  end;

  WebViewClass = interface(NSViewClass)
  ['{0D9F44B7-09FD-4E35-B96E-8DB71B9A2537}']
    {class} function canShowMIMEType(MIMEType: NSString): Boolean; cdecl;
  end;

  WebView = interface(NSView)
  ['{C36D8016-2FCB-49F0-BA1C-C9913A37F9AC}']
    procedure clos; cdecl;
    procedure setHostWindow(hostWindow: NSWindow); cdecl;
    function initWithFrame(frame: NSRect; frameName: NSString; groupName: NSString): Pointer; cdecl;
    function mainFrame: WebFrame; cdecl;
  end;
  TWebView = class(TOCGenericImport<WebViewClass, WebView>)  end;

And here follows to code to construct a WebView:

procedure TForm2.Button1Click(Sender: TObject);
var
  PWebView: Pointer;
  FwkMod: HMODULE;
  MyWebView: WebView;
  urlStr: NSURL;
  urlreq: NSURLRequest;
const
  WebKitFWK: string = '/System/Library/Frameworks/WebKit.framework/WebKit';
begin
  FwkMod := System.SysUtils.LoadLibrary(PWideChar(WebKitFWK));
  PWebView := TWebView.Alloc.initWithFrame(MakeNSRect(10, 10, 300, 300), nil, nil);
  MyWebView := TWebView.Wrap(PWebView);

  urlStr := TNSURL.Create;
  urlstr.initWithString(NSSTR('http://google.com.au/'));
  urlreq := TNSURLRequest.Create;
  urlreq.initWithURL(urlstr);
  MyWebView.mainFrame.loadRequest(urlreq);
end;

The code executes without raising any exceptions, but just does not want to appear. What needs to be done differently in Delphi? The examples I found for objective C appears to be quite simple:

Some objective C examples I have seen mention IBOutlets. It does not look like this is relevant for Delphi.

How to make WebView OSX Xcode project load a URL on launch?

Thanks.


Source: (StackOverflow)

List of Delphi language features and version in which they were introduced/deprecated

Before I begin, I would like to point out that I have honestly and genuinely searched repeatedly and exhaustively via Google for such a thing, and been unable to find one.

I require (for a project I'm developing) a list of all Delphi (2007 to XE2, I no longer support any version older than 2007) "Language Features", and the versions in which they were introduced and (where applicable) deprecated, improved or removed.

I have noted similar questions to this on Stack Overflow before, though most of those were phrased in the form of "which feature is best", and closed as deemed unsuitable.

If anyone knows of such a list (or has enough spare time to compile one), I would be very greatful.

The accepted answer will either contain a link to such a list, or the list itself.


Source: (StackOverflow)

Find out what process registered a global hotkey? (Windows API)

As far as I've been able to find out, Windows doesn't offer an API function to tell what application has registered a global hotkey (via RegisterHotkey). I can only find out that a hotkey is registered if RegisterHotkey returns false, but not who "owns" the hotkey.

In the absence of a direct API, could there be a roundabout way? Windows maintains the handle associated with each registred hotkey - it's a little maddening that there should be no way of getting at this information.

Example of something that likely wouldn't work: send (simulate) a registered hotkey, then intercept the hotkey message Windows will send to the process that registered it. First, I don't think intercepting the message would reveal the destination window handle. Second, even if it were possible, it would be a bad thing to do, since sending hotkeys would trigger all sorts of potentially unwanted activity from various programs.

It's nothing critical, but I've seen frequent requests for such functionality, and have myself been a victim of applications that register hotkeys without even disclosing it anywhere in the UI or docs.

(Working in Delphi, and no more than an apprentice at WinAPI, please be kind.)


Source: (StackOverflow)

How do you extract local variable information (address and type) from a Delphi program or the compiler-generated debug info?

My goal is:

  • Given a suspended thread in a Delphi-compiled 32 or 64-bit Windows program, to walk the stack (doable)
  • Given stack entries, to enumerate the local variables in each method and their values. That is, at the very least, find their address and type (integer32/64/signed/unsigned, string, float, record, class...) the combination of which can be used to find their value.

The first is fine and it's the second that this question is about. At a high level, how do you enumerate local variables given a stack entry in Delphi?


At a low level, this is what I've been investigating:

RTTI: does not list this kind of information about methods. This was not something I actually ever thought was a realistic option, but listing here anyway.

Debug information: Loading the debug info produced for a debug build.

  • Map files: even a detailed map file (a text-format file! Open one and have a look) does not contain local variable info. It's basically a list of addresses and source file line numbers. Great for address to file&line correlation, e.g. the blue dots in the gutter; not great for more detailed information
  • Remote debugging information (RSM file) - no known information on its contents or format.
  • TD32/TDS files: my current line of research. They contain global and local symbols among a lot of other information.

The problems I'm encountering here are:

  • There's no documentation of the TD32 file format (that I can find.)
  • Most of my knowledge of them comes from the Jedi JCL code using them (JclTD32.pas) and I'm not sure how to use that code, or whether the structures there are extensive enough to show local vars. I'm pretty certain it will handle global symbols, but I'm very uncertain about local. There are a wide variety of constants defined and without documentation for the format, to read what they mean, I'm left guessing. However, those constants and their names must come from somewhere.
  • Source I can find using TDS info does not load or handle local symbols.

If this is the right approach, then this question becomes 'Is there documentation for the TDS/TD32 file format, and are there any code samples that load local variables?'

A code sample isn't essential but could be very useful, even if it's very minimal.


Source: (StackOverflow)

Studies of relative costs for development in different languages

Has anyone seen a recent (and fairly balanced) study into the relative costs for software development using differing languages ? I would particular like to see the relative costs of Java Vs. C# Vs. Delphi.


Source: (StackOverflow)

How do I include a newline character in a string in Delphi?

I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?


Source: (StackOverflow)

Why is it bad practice to call an eventhandler from code?

Say you have a menu item and a button that do the same task. Why is it bad practice to put the code for the task into one control's action event and then make a call to that event from the other control? Delphi allows this as does vb6 but realbasic doesn't and says you should put the code into a method that is then called by both the menu and the button


Source: (StackOverflow)

Is there a way to programmatically tell if particular block of memory was not freed by FastMM?

I am trying to detect if a block of memory was not freed. Of course, the manager tells me that by dialog box or log file, but what if I would like to store results in a database? For example I would like to have in a database table a names of routines which allocated given blocks.

After reading a documentation of FastMM I know that since version 4.98 we have a possibility to be notified by manager about memory allocations, frees and reallocations as they occur. For example OnDebugFreeMemFinish event is passing to us a PFullDebugBlockHeader which contains useful informations. There is one thing that PFullDebugBlockHeader is missing - the information if the given block was freed by the application.

Unless OnDebugFreeMemFinish is called only for not freed blocks? This is which I do not know and would like to find out.

The problem is that even hooking into OnDebugFreeMemFinish event I was unable to find out if the block was freed or not.

Here is an example:

program MemLeakTest;

{$APPTYPE CONSOLE}

uses
  FastMM4, ExceptionLog, SysUtils;


procedure MemFreeEvent(APHeaderFreedBlock: PFullDebugBlockHeader; AResult: Integer);
begin
//This is executed at the end, but how should I know that this block should be freed
//by application? Unless this is executed ONLY for not freed blocks.
end;

procedure Leak;
var
  MyObject: TObject;
begin
  MyObject := TObject.Create;
end;

begin
  OnDebugFreeMemFinish := MemFreeEvent;
  Leak;
end.

What I am missing is the callback like:

procedure OnMemoryLeak(APointer: PFullDebugBlockHeader);

After browsing the source of FastMM I saw that there is a procedure:

procedure LogMemoryLeakOrAllocatedBlock(APointer: PFullDebugBlockHeader; IsALeak: Boolean);

which could be overriden, but maybe there is an easier way?


Source: (StackOverflow)

The application was unable to start correctly (0xc000007b)

I have a client/server app which I have been developing on a single PC. Now it needs two serial ports, so I borrowed a PC from a friend.

When I build my app and try to run or debug it (whether in the Delphi IDE or from Windows File manager), it errors "The application was unable to start correctly (0xc000007b)".

Googling doesn't bring up much, but seems to indicate that this is nothing Delphi specific and happens with other apps. It seems to be caused by calling into a 32 bit DLL from a 64 bit app or vice versa.

  • both PCs are Windows 7, 64 bit
  • both have Delphi Xe2 starter edition which can only handle 32 bits
  • The app runs fine on my PC, but not on my friend's
  • Other Delphi apps run just fine on my friend's PC

Can anyone give me a hint as to how to track this down?


Source: (StackOverflow)

How to create "No Activate" form in Firemonkey

In XCode by adding these methods to your NSView subclass can prevent the window from becoming active when clicking on it:

- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent )theEvent {
    return YES;
}
- (BOOL)acceptsFirstMouse:(NSEvent )theEvent {
    return YES; 
}
- (void)mouseDown:(NSEvent )theEvent {
    [[[NSApp]] preventWindowOrdering]; 
}

In Windows platform It is done by this simple code:

HWND hWnd = FindWindowW((String("FM") + fmxForm->ClassName()).c_str(), 
    fmxForm->Caption.c_str());

SetWindowLong(hWnd, GWL_EXSTYLE,
    GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_NOACTIVATE);

How can I subclass NSView to prevent my FMX TForm becoming active when clicking on it?

How can I create "No Activate" form in firemonkey?


Source: (StackOverflow)