我写了个简单的dll例子,以熟悉dll编程。
example.dll源码如下:
library example;uses
  SysUtils,
  Classes;
{$R *.res}
function InStr(SourceStr: integer;Ch: Char): Integer; export;
var
Len,i: Integer;
begin
{Len := strlen(SourceStr);
for i := 0 to Len-1 do
if SourceStr[i] = ch then
begin
Result := i;
Exit;
end;
 }
Result := -1;
end;
exports
Instr  ;begin
end.
////////////////////////////////
在下面的代码中动态调用 example.dll,但不知为什么,程序最后总是提示’ access violation at 0X000000 read of address 0x000000'
unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
 TInStr = function(Source: integer;Check: Char): Integer;stdcall;
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
var
moudle:Thandle;
fun:farproc ;
order: Integer;
aa:pchar;
begin
moudle := loadlibrary('example');
if moudle >32  then begin
  fun:=getprocaddress(moudle,'Instr');
  //aa:=stralloc(80);
  //aa:=strpcopy(aa,edit1.text);
  order:=TInStr(fun)(strtoint(self.Edit1.text),'c');
// showmessage(inttostr(order));end;
freelibrary(moudle);
end;end.请帮我找找原因,谢谢!另外我想问一下,是不是在dll中处理字符串不大方便?

解决方案 »

  1.   

    library example;uses
      SysUtils,
      Classes;
    {$R *.res}
    function InStr(SourceStr: integer;Ch: Char): Integer; stdcall;
    var
    Len,i: Integer;
    begin
    {Len := strlen(SourceStr);
    for i := 0 to Len-1 do
    if SourceStr[i] = ch then
    begin
    Result := i;
    Exit;
    end;
     }
    Result := -1;
    end;
    exports
    Instr  ;begin
    end.
      

  2.   

    如果用String,需要这样:
    library example;uses
      ShareMem,
      SysUtils,
      Classes;
    {$R *.res}
    function InStr(SourceStr: string;Ch: Char): Integer; stdcall;
      

  3.   

    library example;uses
      SysUtils,
      Classes;
    {$R *.res}
    function InStr(SourceStr: integer;Ch: pChar): Integer; stdcall;字符串一般用pChar类型,如果只是delphi调用直接string就可以!
      

  4.   

    On Windows, if a DLL exports routines that pass long strings or dynamic arrays as parameters or function results (whether directly or nested in records or objects), then the DLL and its client applications (or DLLs) must all use the ShareMem unit. The same is true if one application or DLL allocates memory with New or GetMem which is deallocated by a call to Dispose or FreeMem in another module. ShareMem should always be the first unit listed in any program or library uses clause where it occurs.ShareMem is the interface unit for the BORLANDMM.DLL memory manager, which allows modules to share dynamically allocated memory. BORLANDMM.DLL must be deployed with applications and DLLs that use ShareMem. When an application or DLL uses ShareMem, its memory manager is replaced by the memory manager in BORLANDMM.DLL.