![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
Использование функции из DLLDelphi , Файловая система , DLL и PlugInsАвтор: Xavier Pacheco { Copyright © 1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira } library StrSrchLib; uses Wintypes, WinProcs, SysUtils, Dialogs; type { declare the callback function type } TFoundStrProc = procedure(StrPos: PChar); StdCall; function SearchStr(ASrcStr, ASearchStr: PChar; AProc: TFarProc): Integer; stdcall; { This function looks for ASearchStr in ASrcStr. When if finds ASearchStr, the callback procedure referred to by AProc is called if one has been passed in. The user may pass nil as this parameter. } var FindStr: PChar; begin FindStr := ASrcStr; FindStr := StrPos(FindStr, ASearchStr); while FindStr <> nil do begin if AProc <> nil then TFoundStrProc(AProc)(FindStr); FindStr := FindStr + 1; FindStr := StrPos(FindStr, ASearchStr); end; end; exports SearchStr; begin end. { Copyright © 1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira } unit MainFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMainForm = class(TForm) btnCallDLLFunc: TButton; edtSearchStr: TEdit; lblSrchWrd: TLabel; memStr: TMemo; procedure btnCallDLLFuncClick(Sender: TObject); end; var MainForm: TMainForm; Count: Integer; implementation {$R *.DFM} { Define the DLL's exported procedure } function SearchStr(ASrcStr, ASearchStr: PChar; AProc: TFarProc): Integer; stdcall external 'STRSRCHLIB.DLL'; { Define the callback procedure, make sure to use the StdCall directive } procedure StrPosProc(AStrPsn: PChar); stdcall; begin inc(Count); // Increment the Count variable. end; procedure TMainForm.btnCallDLLFuncClick(Sender: TObject); var S: string; S2: string; begin Count := 0; // Initialize Count to zero. { Retrieve the length of the text on which to search. } SetLength(S, memStr.GetTextLen); { Now copy the text to the variable S } memStr.GetTextBuf(PChar(S), memStr.GetTextLen); { Copy Edit1's Text to a string variable so that it can be passed to the DLL function } S2 := edtSearchStr.Text; { Call the DLL function } SearchStr(PChar(S), PChar(S2), @StrPosProc); { Show how many times the word occurs in the string. This has been stored in the Count variable which is used by the callback function } ShowMessage(Format('%s %s %d %s', [edtSearchStr.Text, 'occurs', Count, 'times.'])); end; end. Программа на Delphi использует DLL (динамическую связку библиотеки) для поиска строки в другой строке и выполнения действия каждый раз, когда searched строка найдена. Разбивка работы программы:
Функция использует цикл для итерации над символами
Преимущества использования DLL в этом случае:
Однако использование DLL также добавляет сложность программы, поскольку вам нужно управлять аллокацией и deallocation памяти, а также обрабатывать ошибки, которые могут возникнуть при взаимодействии между GUI-приложением и DLL. В статье описывается использование функции из DLL-библиотеки StrSrchLib для поиска строки ASearchStr в строке ASrcStr и вызова callback-процедуры при каждом ее обнаружении. Комментарии и вопросыПолучайте свежие новости и обновления по Object Pascal, Delphi и Lazarus прямо в свой смартфон. Подпишитесь на наш Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта. :: Главная :: DLL и PlugIns ::
|
||||
©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007 |