近日刚学dll,从书上抄了一个例子,却运行不了,执行到Order:=TInstr(PFunc)(text,key);时提示非法操作,----------------------------------------------------------------
library example;
uses
  SysUtils,
  Classes;{$R *.res}function InStr(SourceStr:PChar;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.----------------------------------------------------------------------
调用:unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
  Tinstr= function(source:pchar;check:char):Integer;
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Label1: TLabel;
    procedure Edit2KeyPress(Sender: TObject; var Key: Char);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Edit2KeyPress(Sender: TObject; var Key: Char);
var order:Integer;
    text:PChar;
    PFunc:TFarProc;
    Module:THandle;
begin
  Module:=LoadLibrary('example.dll');
  if Module>32 then
     begin
        Edit2.Text:='';
        PFunc:=GetProcAddress(Module,'Instr');
        text:=StrAlloc(80);
        text:=strPcopy(text,Edit1.text);
        Order:=TInstr(PFunc)(text,key); //运行到此处提示非法操作
        if order =-1 then
           label1.Caption:='no this char;'
         else label1.Caption:=InttoStr(order);
     end;
  Freelibrary(Module);
end;end.

解决方案 »

  1.   

    library example;uses
      SysUtils,
      Classes;{$R *.res}function InStr(SourceStr:PChar;ch:char):Integer;export;一般,我用的是如下:
    function InStr(SourceStr:PChar;ch:char):Integer;stdcall;你在Unit1中的申明要要一样,另外,要注意函数的大小写!
    你在: 
    PFunc:=GetProcAddress(Module,'Instr');
    中,也要判断PFunc是不是nil,如果是,那就是说找不到,那下面的当然有问题了!
    检查下 是 Instr 还是 InStr?
      

  2.   

    直接Order := InStr(PChar(Edit1.Text), Key);有没有问题?
      

  3.   

    你没有进行声明就进行了调用,你需要在interface声明;
    function InStr(SourceStr:PChar;ch:char):Integer;stdcall;external 'example.dll';