Point to a DLL using a dynamic path - delphi

My problem is not exporting a function, but importing it. I know for sure that both the function and DLL both work because I have used a hard-coded path to point to the DLL.
This is what is currently working:
function RoamingAppDataPath: String; external 'C:\Users\Peter\AppData\Roaming\ss\Application\ss.dll';
However I need to point to the DLL with a dynamic value so what I tried to do is
Declare a global variable (DLLPath: String)
Assign DLLPath the value - RoamingAppDataPath+'\ss\Application\ss.dll'
Note: RoamingAppDataPath is a function that outputs the path to the roaming app data folder.
The code I am trying to run is:
function RoamingAppDataPath: String; external DLLPath;
When I compile the code, Delphi is telling me that it is expecting a constant expression:
E2026 Constant expression expected
What is the work around for this?

You have to bind at runtime and that means you need to use LoadLibrary and GetProcAddress:
var
lib: HMODULE;
RoamingAppDataPath: function: string;
lib := LoadLibrary(dllfilename);
if lib=0 then
RaiseLastOSError;
Pointer(RoamingAppDataPath) := GetProcAddress(lib, 'RoamingAppDataPath');
And then you can call it:
radp := RoamingAppDataPath;
Some comments:
I don't know why you write this function when it exists in standard system libraries.
Using string across DLL boundaries is liable to fail. You need to be using ShareMem and make sure that all code is built with the same Delphi version. Better to allocate the buffer in the calling code.

Even if you would be able to use a Variable, you would nowhere be able to set a value to DLLPATH, since already initalization would not be used if a static DLL can not be used.
You will have to use dynamic loadingif you want to define the path for the DLL.
procedure Test;external 'Notexists.DLL';
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
test;
end;
initialization
Showmessage('Hallo'); // will never be seen if test is used.

Related

Dynamicly handle not defined functions in a dll in dlephi

I have a dll which defines a simple functions to show a message:
library testdll;
uses SysUtils, Classes, Dialogs;
{$R *res}
procedure ShowDll;stdcall;
begin
ShowMessage('ShowDLL testdll.dll');
end;
exports ShowDLL;
begin
end.
And my main file call this dll dynamicly using this procedure:
i defined a new type:
type
testdll = procedure;stdcall;
Then on my button click event:
procedure TForm1.Button1Click(Sender:TObject);
var
dllHandle: THandle; //Don't use Cardinal; it's limited to 32-bits
test : testdll;
begin
dllHandle := LoadLibrary('testdll.dll');
if dllHandle <> 0 then
begin
#test := GetProcAddress(dllHandle,'ShowDLL');
if Assigned(test) then
ShowDLL
else
ShowMessage('Func not found');
end
else
ShowMessage('dll not found');
end;
This works. But I don't know if it's possible to handle not defined functions with my dll. My purpose here is to call a function without knowing if it will be defined in my dll. So i would like the dll to tell me if the functions exists or not.
For example here i only have a ShowDLL procedure. If i call another method which does not exists it will show 'Func not found' from my main application. But i would my dll to tell me this. Is this possible? If yes, how could i achieve this pls?
EDIT: I can't modify the main function this is only a test. In my final version there will be only the dll. So exporting all functions into my main application is not possible here. That's why i want to know id the dll alone can handle it rather than doing this in my main application which i can't do.
I don't have acces to the main application to modify any code in it. I only know what are functions that will be used in this application that i will later export in my dll using exports statement. So what i try to achieve is to catch a not defined function with the dll if it's possible.
Your code already demonstrates how to detect the presence of an export. Namely to call GetProcAddress and compare the result with nil.
You can reduce the amount of boiler plate code by using delay loading. This essentially lets the compiler generate the code the performs the checks. This relies on the delayed keyword.
procedure testdll; stdcall;
external 'testdll.dll` delayed;
When you call this function, if it cannot be found, an exception is raised. Indeed this behaviour can be customised, as described in the documentation: http://docwiki.embarcadero.com/RADStudio/en/Libraries_and_Packages#Delayed_Loading
Update
In a comment to this answer you state that the executable cannot be changed. In which case, the message that you wish to avoid will be shown if the function is missing. You ask if the missing export can be handled by the DLL but that is not possible. When you call GetProcAddress, no code inside the DLL is executed. All the processing is done external to the DLL by reading its PE metadata.
The obvious conclusion is that the DLL must export the function. If the true DLL does not, put another DLL in its place. Use an interposer DLL that exports the function. Implement the function by delegating to the true DLL, if the true DLL exports the function. Otherwise do something else, whatever you please.

Directory path manipulation in Delphi?

I have the full path name of a given folder for e.g.
c:\foo\bar
Now I would like to reference a file inside c:\foo named baz.txt,
c:\foo\bar\..\baz.txt
I am currently using the .. path operator to go down one level and get the file that I need.
Is there a function that can do path manipulations, for e.g. UpOneLevel(str) -> str ? I know I can write one by splitting the string and removing the last token, but I would rather it be a built-in / library function so I don't get into trouble later if there are for e.g. escaped backslashes.
Use the ExpandFileName function:
var
S: string;
begin
S := 'c:\foo\bar\..';
S := ExpandFileName(S);
ShowMessage(S);
end;
The message from the above example will show the c:\foo path.
Look at ExtractFilePath() and ExtractFileDir(). These are available in just about all Delphi versions, particularly those that do not have TDirectory, IOUtils, etc.
And before anyone says it, these work just fine whether the path ends with a filename or not. ForceDirectories() uses them internally to walk backwards through a hierarchy of parent folders, for example.
This answer is valid for Delphi XE +
Use the TDirectory class of the IOutils unit, which have the method GetParent, like this::
uses IOUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
begin
s := 'c:\foo\bar';
ShowMessage(TDirectory.GetParent(s));
end;
In older versions
Look at the other answers.
You can take a look at TPathBuilder record in SvClasses unit from delphi-oop library. This unit does not support Delphi 2007 but TPathBuilder implementation is compatible with this Delphi version. Example usage:
var
LFullPath: string;
begin
LFullPath := TPathBuilder.InitCustomPath('c:\foo\bar').GoUpFolder.AddFile('baz.txt').ToString;
//LFullPath = c:\foo\baz.txt

Free Pascal can't find entry point for dll

I am complete new to pascal.
I want to call my function in .dll file in free pascal and I get following error when I run the project:
The procedure entry point GetProcAddress could not be located in the dynamic link library HNLib.dll.
here is the code:
Program Test;
function GetProcAddress : Integer; cdecl; external 'HNLib.dll';
function GetProcAddress : Single; cdecl; external 'HNLib.dll';
procedure GetProcAddress( X : Single); cdecl; external 'HNLib.dll';
procedure GetProcAddress; cdecl; external 'HNLib.dll';
begin
GetProcAddress( 5.5 );
readln;
end.
.pas file and dll are in one directory.
Please Help ME!
GetProcAddress is not what you seem to think it is; it's purpose is to locate named procedures or functions in a DLL and return the address of that function so it can be called from your code. You have to first use LoadLibrary to load the dynamic link library (DLL) into memory, and then pass a handle to that DLL as the first parameter of GetProcAddress and the name of the function whose address you want as the second parameter. If the function can be found in the DLL, it's address is returned, and you can use that address to call the function.
(In addition, GetProcAddress is pretty Windows-specific, and the majority of functions in the WinAPI are stdcall and not cdecl. Unless you have documentation saying that the functions are using the cdecl calling convention, you should probably use stdcall.)
You would also need at least the Windows unit in your uses clause, since that's where GetProcAddress and LoadLibrary are declared.
See the WinAPI documentation on LoadLibrary and GetProcAddress for more information.
For a beginning programmer, you'll probably find it easier to use static linking of the functions instead of dynamic (which you get with GetProcAddress). An example of static linking would be (untested !!!- just a quick code example, since I don't have 'HNLib.DLL' to link against):
// Your Dll import unit
unit MyDllProcs;
interface
function GetIntCalcResult(const IntVal: Integer);
implementation
function GetIntCalcResult(const IntVal: Integer); stdcall; external 'HNLib.dll';
end.
// Your own app's code
program Test;
interface
uses MyDllProcs;
implementation
function DoSomethingWithDll(const ValueToCalc: Integer): Integer;
begin
Result := GetIntCalcResult(ValueToCalc);
end;
begin
WriteLn('DoSomethingWithDll returned ', DoSomethingWithDll(10));
ReadLn;
end.
Note that when statically linking DLL functions like this, your DLL must be available when your app starts, and the function must be contained in that DLL; if not, your application won't load.
Also, note that you can't typically have multiple functions with the same name in the DLL, as there's no information available to use to figure which one to load when the load is being done. Each should have a separate, distinct name or the loading will probably fail.

Is it safe to pass Delphi const string params across memory manager boundaries?

Subj. I'd like to use strings instead of PChar because that spares me much casting, but if I just do
procedure SomeExternalProc(s: string); external SOMEDLL_DLL;
and then implement it in some other project with non-shared memory manager:
library SeparateDll;
procedure SomeExternalProc(s: string);
begin
//a bla bla bla
//code here code here
end;
I have (formally) no guarantee Delphi does not decide for whatever reason to alter the string, modify its reference counter, duplicate or unique it, or whatever else. For example
var InternalString: string;
procedure SomeExternalProc(s: string);
begin
InternalString := s;
end;
Delphi increments refcounter and copies a pointer, that's it. I'd like Delphi to copy the data. Does declaring the parameter as "const" make it safe for that reason? If not, is there a way to do it? Declaring parameter as PChar doesn't seem to be a solution because you need to cast it every time:
procedure SomeExternalProc(s: Pchar); forward;
procedure LocalProc;
var local_s: string;
begin
SomeExternalProc(local_s); //<<--- incompatible types: 'string' and 'PAnsiChar'
end;
That would probably work, as long as you only ever use your DLL from code compiled in the same version of Delphi. The internal format of string has been known to change between releases, and you have no formal guarantee that it won't change again.
If you want to avoid having to cast everywhere you use it, try wrapping the function, like this:
procedure SomeExternalProc(s: Pchar); external dllname;
procedure MyExternalProc(s: string); inline;
begin
SomeExternalProc(PChar(local_s));
end;
Then in your code, you call MyExternalProc instead of SomeExternalProc, and everyone's happy.
If both the app and the DLL are written in the same Delphi release, just use shared memory manager (more details here).
If one side is written in a different language than there's no other way but to use PChar or WideString (WideStrings are managed by the COM memory manager).
Or you can write a wrapper function:
procedure MyExternalProc(const s: string);
begin
SomeExternalProc(PChar(s));
end;
Just to add a single fact:
Delphi allows you to simply assign PChar to a string so on the DLL side you don't need any typecast:
function MyDllFunction(_s: PChar): integer;
var
s: string;
begin
s := _s; // implicit conversion to string
// now work with s instead of the _s parameter
end;
This also applies for passing PChar as a parameter to a function that expects a (by value) string.
I recommend to use an alternative memory manager such as RecyclerMM or FastMM. They doesn't require any external shared MM dll's and allows you to pass strings to the dlls safely. As a bonus, you may get a nice performance improvement in whole application.
FastMM is used as a default memory manager in Delphi 2006 and above. Also it's a good tool to search the memory-leaks.

Accessing Sub functions /procedures from DPR or other function / procedure in Delphi

As much I know - Subroutines are with Private access mode to its parent unction / procedure, right?
Is there any way to access them from "outer-world" - dpr or other function / procedure in unit?
Also - which way takes more calcualtion and space to compiled file?
for example:
function blablabla(parameter : tparameter) : abcde;
procedure xyz(par_ : tpar_);
begin
// ...
end;
begin
// ...
end;
procedure albalbalb(param : tparam) : www;
begin
xyz(par_ : tpar_); // is there any way to make this function public / published to access it therefore enabling to call it this way?
end;
// all text is random.
// also, is there way to call it from DPR in this manner?
// in C++ this can be done by specifing access mode and/or using "Friend" class .. but in DELPHI?
Nested procedures/functions - those declared inside another procedure or function, are a special type, because they can access the stack (and thereby parameters/local variables) of the procedure they are nested in. Because of this, and Delphi scope rules, there is no way to access them outside the "parent" procedure. You use them only if you need to take advantage of their special features. AFAIK Delphi/Pascal is one of the few languages to have this feature. From a compiler point of view the call has some extra code to allow accessing the parent stack frame, IIRC.
AFAIK "friend" class/functions in C++ are different - they are class access methods, while in your example you are using plain procedures/functions.
In Delphi all procedure/classes declared in the same unit are automatically "friend", unless strict private declarations are used in latest Delphi releases. For example this code snippets will work, as long everything is in the same unit:
type
TExample = class
private
procedure HelloWorld;
public
...
end;
implementation
function DoSomething(AExample: TExample);
begin
// Calling a private method here works
AExample.HelloWordl;
end;
Note: Embedded Routines <> Private/Protected Methods.
Embedded routines i.e. routines inside routines can not be accessed by external routines.
You have posted an example of an Embedded routine, I also heard them called Internal Routines.
Here is another example:
procedure DoThis;
function DoThat : Boolean;
begin
// This Routine is embedded or internal routine.
end;
begin
// DoThat() can only be accessed from here no other place.
end;
Regardless of visibility, methods on classes, can be called using Delphi 2010 via RTTI. I have detailed how to do this in this article.
If you are in the same Unit methods on a class can be accessed by any other code regardless of visibility, unless they are marked with Strict Private. This Question has more details and good example code in the accepted answer.
If you are in two different units you can use the Protected Method Hack to access the protected methods. Which is detailed in detailed in this article.
Yes, you can access a subroutine, which is nested in other (parent) subroutine, from the outer world. Though it's somewhat tricky. I've found this howto in the web.
How to pass nested routine as a procedural parameter (32 bit)
Delphi normally does not support passing nested routines as procedural parameters:
// This code does not compile:
procedure testpass(p: tprocedure);
begin
p;
end;
procedure calltestpass;
procedure inner;
begin
showmessage('hello');
end;
begin
testpass(inner);
end;
The obvious workaround is to pass procedure address and typecast it within testpass:
// This code compiles and runs OK
procedure testpass(p: pointer);
begin
tProcedure(p);
end;
procedure calltestpass;
procedure inner;
begin
showmessage('hello');
end;
begin
testpass(#inner);
end;
There is, however, a pitfall in the above example - if the "inner" routine references any variable that was pushed onto the stack before the "inner" procedure was called from testpass (calltestpass parameters - if there were any, or local variables in calltestpass - if there were any), your system most probably crashes:
// This code compiles OK but generates runtime exception (could even be
// EMachineHangs :-) )
procedure testpass(p: pointer);
begin
tProcedure(p);
end;
procedure calltestpass;
var msg: string;
procedure inner;
begin
msg := 'hello';
showmessage(msg);
end;
begin
testpass(#inner);
end;
The reason is, in simple words, that the stack frame arrangement
was "broken" by the call to testpass routine and "inner" procedure
incorrectly calculates parameters and local variables location
(do not blame Delphi, please).
The workaround is to set up the correct stack context before
"inner" is called from within "testpass".
// This code compiles and runs OK
{$O-}
procedure testpass(p: pointer);
var callersBP: longint;
begin
asm // get caller's base pointer value at the very beginning
push dword ptr [ebp]
pop callersBP
end;
// here we can have some other OP code
asm // pushes caller's base pointer value onto stack and calls tProcedure(p)
push CallersBP
Call p
Pop CallersBP
end;
// here we can have some other OP code
end;
{$O+}
procedure calltestpass;
var msg: string;
procedure inner;
begin
msg := 'hello';
showmessage(msg);
end;
begin
testpass(#inner);
end;
Please note the optimization is switched OFF for testpass routine - optimization generally does not handle mixed OP/assembler code very well.
No, there is no way to do what you're asking. The xyz function is callable only by the enclosing blablabla function. Outside that function, xyz is not in scope and there is no way to name it. If C++ allowed nested function, there wouldn't be any way to refer to it, either, just like there's no way to refer to functions with static linkage from outside the current translation unit.
If you need to call xyz from outside the blablabla function, then move xyz outside. If you need to call it from outside the current unit, then you need to declare that function in the unit's interface section. Then, add that unit to the external code's uses clause and you can call xyz from wherever you want, even the DPR file.
If xyz refers to variables or parameters of the blablabla function, then you'll need to pass them in as parameters since xyz will no longer have access to them otherwise.
The concept of access specifiers isn't really relevant here since we're not talking about classes. Units have interface and implementation sections, which aren't really the same as public and private sections of a class.

Resources