zoukankan      html  css  js  c++  java
  • delphi 创建DLL文件 及其调用和注意事项

    首先创建一个DLL文件,项目自带的代码为:

    library ProjectPnr;
    
    { Important note about DLL memory management: ShareMem must be the
      first unit in your library's USES clause AND your project's (select
      Project-View Source) USES clause if your DLL exports any procedures or
      functions that pass strings as parameters or function results. This
      applies to all strings passed to and from your DLL--even those that
      are nested in records and classes. ShareMem is the interface unit to
      the BORLNDMM.DLL shared memory manager, which must be deployed along
      with your DLL. To avoid using BORLNDMM.DLL, pass string information
      using PChar or ShortString parameters. }
    
    uses
      SysUtils,
      Classes,
    
    //再在Uses下声明一个函数:
    function Add(a, b: integer):integer; // 函数功能 实现a,b相加
    begin
       result := a + b;   
    end

    exports add; // 必须要有这句才能输出 begin end.

     这样一个简单的dll就创建成功了,保存为test,建议最好把建好的dll放在和调用项目放在一起,

     接下来就是调用了,调用很简单:

    新建一个application,在implementation上面引用刚刚写的dll函数:

    function apnr(a,b: integer):integer; external 'test.dll';
    

     这里注意,大小写要和dll里的函数一样。

    放一个按钮,在OnClick事件中调用dll里函数就行。

    procedure TForm2.Button1Click(Sender: TObject);
    begin
     ShowMessage(add(1, 2));     //3
    end;
    

    但是当返回值是string时,调用会报指针内存错误,比如说:(至少在delphi7里)

    //dll里函数
    function add(a, b: integer): string;
    begin
      result := IntToStr(a + b);
    end;
    

    解决方法:

    将返回值string改成PChar,就可以调用了,应该是dll的处理string和application处理string的方法不一样吧。

    然后我将用XE打开刚刚调用dll的项目,发现直接闪退,我在用D7打开这个项目,结果有返回值,

    这种现象是因为D7的PChar长度是单字节,而XE的PChar长度是双字节,具体用SizeOf测试,D7用的是Ansi编码,XE用的时Unicode编码,

    解决方法

    把PChar改成PAnsiChar或PWideChar。

    为了兼容,最好把dll要返回的string变成PAnsiChar。

  • 相关阅读:
    @@IDENTITY 存储过程
    ASP.NET的Cookie和Session
    数据格式设置表达式
    DataTable类(MSDN)
    用静态变量代替appliction
    C cgi url 编码解码问题
    C#视频头操作
    c#网页抓取
    c语言字符串分隔
    CGI c 上传文件
  • 原文地址:https://www.cnblogs.com/studypanp/p/4970999.html
Copyright © 2011-2022 走看看