zoukankan      html  css  js  c++  java
  • delphi 给字符指针分配内存

    今天,对接第三方dll的时候出现如下问题:

    接口声明如下:

    long BL_tradeBalance (char *MerchantNumber,char *PosId,char *OperatorNumber,

                                        int TypeCode,int PrintMode,

    char *ResponseBuf,char *retCode,char *retMsg)

    输入参数

       char mMerchantNumber[6]        //商户号(门店号)

       char mPosId[3]                 //pos机号(终端号)

       char mOperatorNumber[20];       //操作员号

       int TypeCode;                               //业态标识  1

       int PrintMode;                  //打印模式  1

    输出参数

       char ResponseBuf[2048]        //f返回当日对账明细

       char retCode [20]               //返回码

       char retMsg [256]              //返回信息

     ----------------------------------------------------------------------------------------

    delphi端调用

      var

         resBuf,retCode,retMsg: PChar;

       调用:

         dev.BL_tradeBalance(Pchar(sStoreNo),PChar(FPosNo),PChar(FEmpCode),1,1,resBuf,retCode,retMsg)

       报dll异常

      此时需要我们给返回的指针主动分配内存

       resBuf := StrAlloc(2048);
       retCode := StrAlloc(20);
       retMsg := StrAlloc(256);

    如果不是对接方主动说明,一般需要我们主动给返回值分配内存,然后做好释放工作

    --------------------------------------------------------------------------------

       resBuf := StrAlloc(2048);
       retCode := StrAlloc(20);
       retMsg := StrAlloc(256);
       try

          ....

       finally 

           StrDispose(resBuf);
           StrDispose(retCode);
           StrDispose(retMsg);

       end;

    --------------------------------------------------------------------------------

    扩展了解下字符指针内存分配函数

      

    GetMem
    AllocMem
    ReallocMem
    FreeMem
    
    GetMemory
    ReallocMemory
    FreeMemory
    
    New
    Dispose
    
    NewStr
    DisposeStr
    
    StrNew
    StrAlloc
    StrDispose

    给字符指针(PChar、PWideChar、PAnsiChar)分配内存, 最佳选择是: StrAlloc.

    StrAlloc 虽然最终也是调用了 GetMem, 但 StrAlloc 会在指针前面添加 Delphi 需要的 4 个管理字节(记录长度).

    StrAlloc 分配的内存, 用 StrDispose 释放, 用 StrBufSize 获取大小.

    用 FreeMem 释放可以吗? 这样会少释放 4 个字节.

    这种类型的指针一般用于 API 函数的参数, 譬如获取窗口标题:

    var
      p: PChar;
    begin
      p := StrAlloc(256);
      GetWindowText(Handle, p, StrBufSize(p));
      ShowMessage(p); {Form1}
      StrDispose(p);
    end;
    
  • 相关阅读:
    【转载】 HTTP 中 GET 与 POST 的区别
    JS 浏览器cookie的设置,读取,删除
    JS Event事件流(冒泡机制、捕获机制、事件绑定)
    DOM节点树和元素树--深度遍历
    Html_Task4(知识点:水平居中+垂直居中/position/float/border-radius)
    百度前端技术学院—斌斌学院题库
    百度前端技术学院—-小薇学院(HTML+CSS课程任务)
    js正则表达式
    js设计模式(一)发布订阅模式
    vue学习笔记(一)——利用vue-cli搭建一个前端项目
  • 原文地址:https://www.cnblogs.com/lodor/p/6646875.html
Copyright © 2011-2022 走看看