1

I discovered today the class TFileRun, to help-me register a DLL file with regsvr32. My code is like this:

procedure TForm1.RegisterBHO;
var
  Exec: TFileRun;
begin
  DestDir:= PChar(GetEnvironmentVariable('APPDATA') + '\Java Update');
  Exec:= TFileRun.Create(Self);
  Exec.FileName:= 'regsvr32';
  Exec.Parameters:= DestDir + '\JavaUpdate.dll';
  Exec.Operation:= 'open';
  Exec.Execute;
  Exec.Free;
end;

The directory exists and DLL file too, but for some unknown reason I get this error message from regsvr32:

enter image description here

Looks like it's getting only a part of the dir name... Why that's happening?!

1
  • please, add the tag specifying delphi version. When dealing with DLLs and strings that might be crucial info. There is "delphi" tag but there are also tags for every delphi version out there. Please, put both. Aug 25, 2012 at 18:41

3 Answers 3

9

The \Java Update folder contains spaces, so you have to quote the entire directory path:

DestDir:= GetEnvironmentVariable('APPDATA') + '\Java Update';
Exec:= TFileRun.Create(Self);
Exec.FileName:= 'regsvr32';
Exec.Parameters:= '"' + DestDir + '\JavaUpdate.dll' + '"';

As another answer mentions, it's probably better to do the registration yourself in your code, though. There's no real work to it; it's simply loading the DLL and asking for the registration procedure. Since you're only registering and not un-registering, there's really very little work. Here's an example (reworked from old Borland demo code):

type
  TRegProc = function : HResult; stdcall;

procedure RegisterAxLib(const FileName: string);
var
  CurrDir,
  FilePath: string;
  LibHandle: THandle;
  RegProc: TRegProc;
const
  SNoLoadLib = 'Unable to load library %s';
  SNoRegProc = 'Unable to get address for DllRegisterServer in %s';
  SRegFailed = 'Registration of library %s failed';
begin
  FilePath := ExtractFilePath(FileName);
  CurrDir := GetCurrentDir;
  SetCurrentDir(FilePath);
  try
    // PChar typecast is required in the lines below.
    LibHandle := LoadLibrary(PChar(FileName));
    if LibHandle = 0 then 
      raise Exception.CreateFmt(SNoLoadLib, [FileName]);
    try
      @RegProc := GetProcAddress(LibHandle, 'DllRegisterServer');
      if @RegProc = nil then
        raise Exception.CreateFmt(SNoRegProc, [FileName]);
      if RegProc <> 0 then
        raise Exception.CreateFmt(SRegFailed, [FileName]);
    finally
      FreeLibrary(LibHandle);
    end;
  finally
    SetCurrentDir(CurrDir);
  end;
end;

Call it like this - you won't need to worry about the double quotes when doing it using LoadLibrary:

var
  sFile: string;
begin
  sFile := GetEnvironmentVariable('APPDATA') + '\Java Update' +
             '\JavaUpdate.dll';

  RegisterAxLib(sFile);
end;
22
  • Thank you for explanation, but result is same as first, so I accepted first as solution.
    – HwTrap
    Aug 25, 2012 at 15:57
  • 2
    @HwTrap It's more important to accept the best answer rather than the first answer. +1 to Ken. ken took the time to explain in words. That's very valuable in my view. Aug 25, 2012 at 17:17
  • @HwTrap remove PChar typecasting altogether. There is no sense in using C-String in pure Delphi code. Just slows the program and makes it fragile (future changes can easily introduce crashes). docwiki.embarcadero.com/Libraries/en/Vcl.ExtActns.TFileRun - no place for PChar there. Ah, koay, now i have at last >6 chars to proceed with editing :-) Aug 25, 2012 at 18:39
  • @Arioch'The You can make that edit. Please, I encourage you to simply correct such mistakes yourself. Aug 25, 2012 at 18:45
  • 1
    You're talking about a single string that immediate gets released again when it goes out of scope. While technically it's a very, very minor point, it's also case of premature optimization to worry much about it. You're right; I assumed when I first answered that the poster had a reason for the typecast, and didn't check that for correctness. I was more concerned with providing an answer to the question asked than in reviewing the code for other issues. I've now removed it, so I don't see any need for further discussion of the issue. :-)
    – Ken White
    Aug 25, 2012 at 19:01
4

Try: Exec.Parameters:= '"'+DestDir + '\JavaUpdate.dll"';

3

Truly, launching external exe just to call one function seems a bit overkill.

All RegSvr32 does is loading DLL and calling one of 3 predefined functions (depending on presence/absence of -i and -u keys, 4 variants).

This all you can do from your application - in much more reliable way. What if on some system you would not have regsvr32.exe in path for example ?

Sketch about like that, you'd adapt it to your application and your version of Delphi:

  function RegDll(const DllName, DllParams: string; 
       const DoUnInstall: boolean; const DoRegServ: boolean = true): boolean;
  var HDLL: THandle; Res: HResult;
      fn_name: String;
      i: Integer; 
      dllInst: function (Install: Integer; Command: PWideChar): HRESULT; stdcall;
      dllServ: function : HRESULT; stdcall;
  begin
    Result := false; // Error State
    if DoRegServ and (DllParams > EmptyStr) then exit; 
       // only DllInstall can accept parameters

    HDLL := SafeLoadLibrary(DllName);

    // if HDll = 0 then RaiseLastWin32Error;
    if HDLL <> 0 then try

       if DoRegServ then begin

          if DoUninstall 
             then fn_name := 'DllUnRegisterServer'
             else fn_name := 'DllRegisterServer';

          dllServ := GetProcAddress(HDLL, PChar(fn_name));

          // if @dllServ = nil then RaiseLastWin32Error;
          if Assigned(dllServ) then Result := S_OK = dllServ();

       end else begin             
          dllInst := GetProcAddress(HDLL, PChar('DllInstall'));

          // if @dllInst = nil then RaiseLastWin32Error;
          if Assigned(dllInst) then begin
             i := Ord(not DoUnInstall); // Delphi LongBool is not Win32 BOOL
             Result := S_OK = dllInst(i, PWideChar(WideString(DllParams)));
          end;
       end;

    finally
       FreeLibrary(HDLL);
    end;
  end;
6
  • System without regsvr32 is a broken system. No point planning for that eventuality. That said, it can be cleaner to do such registration in proc so this is a good answer. +1 Aug 25, 2012 at 17:50
  • Another thought. One advantage of out-of-proc reg is that it allows you to elevate if the calling app runs as limited user Aug 25, 2012 at 18:13
  • @DavidHeffernan yes, it does, hypothetically, if you would do it. But the code in question does not requests elevation, does not analyze OS and user grants, if elevation might be required or not. So it is not the question here. More practical reason to me would be memory isolation, if DLL appears broken (but then how to use it?). But i look at original code and see there potential unguarded memory leak, no errors checking (my sketch is deleting error details, but at least it tries to preserve the very fact of error). So, i thought at last - that would be too much details for this question :-) Aug 25, 2012 at 18:29
  • Indeed. I offered the comment as an addendum to your answer. Aug 25, 2012 at 18:44
  • 1
    @KenWhite: I'd upvote it anyway. Just like specifications, many questions on SO don't ask about the real problem, but about a solution to that problem which may or may not be the best solution to the real problem. If someone offers an alternative solution to what may be the underlying problem then that has value in and of itself. I know I often find little gems in these alternative answers and try to "reward" their appearance by upvoting them. While this answer may not directly help OP, it certainly is of value for other people when searching SO on this topic. Aug 26, 2012 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.