//生成动态链接库单元
library Example;uses
  SysUtils,
  Classes;{返回字符在串中的位置}
  function InStr(SourceStr:PChar;Ch:Char):Integer;export;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;
beginend.
.........................................................程序执行单元
unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
TInStr = function(Source: PChar;Check: Char): Integer;//定义一函数类型type
  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;
  txt: PChar;
  PFunc: TFarProc;
  Moudle: THandle;
begin
  Moudle := Loadlibrary('C:\Documents and Settings\Administrator\桌面\dynamic\Project1.dll');//
  if Moudle > 32 then
  begin
    Edit2.text := '';
    Pfunc := GetProcAddress(Moudle,'InStr');//
    txt := StrAlloc(80);
    txt := StrPCopy(txt,Edit1.text);
    Order := TInStr(PFunc)(txt,Key);//
    if Order = -1 then
    Label1.Caption := '不包含这个字符 '
    else
    Label1.Caption := '位于第'+IntToStr(Order+1)+'位';
  end;
  Freelibrary(Moudle);
end;
end.
..................................................主工程单元如下
program Project1;uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1};{$R *.res}begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
对于动态调用链接库,上面是一个简单例子。系统一共包含两个编辑框。在第一个编辑框中输入一个字符串,而后在第二个编辑框中输入字符。如果该字符包含在第一个编辑框的字符串中,则标签框显示信息:“位于第n位。”,否则显示信息:“不包含这个字符。”。问题是每次都报“不包含这个字符”且在关闭后还弹出“Exception EAccessViolation in module Project1.exe at 0001913A Access violation at address 041913A in module 'project1.exe'.”
望各位老师指点迷津,谢谢!

解决方案 »

  1.   

    你Debug一下
    看到底是哪出的错啊 
      

  2.   

    TInStr = function(Source: PChar;Check: Char): Integer;//定义一函数类型   function InStr(SourceStr:PChar;Ch:Char):Integer;export;stdcall;//动态链接库函数     定义不一致 
      

  3.   

    问题是每次都报“不包含这个字符”
    为什么不走 Label1.Caption := '位于第'+IntToStr(Order+1)+'位';这个呢?我故意设值让它走这个,它还是不走。
    最后一个//下面的错。
      

  4.   

    这样就好了,测试过了  TInStr = function(Source: PChar;Check: Char): Integer;stdcall;
      

  5.   

    谢谢yuqianyi1974
    就是这个问题,已经解决了。