• 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;
    
  • 相关阅读:
    Hadoop的多节点集群详细启动步骤(3或5节点)
    Hive的单节点集群详细启动步骤
    HDU-1039-Easier Done Than Said?(Java && 没用正則表達式是我的遗憾.....)
    Linux下套接字具体解释(三)----几种套接字I/O模型
    C++晋升之std中vector的实现原理(标准模板动态库中矢量的实现原理)
    POJ 1781 In Danger Joseph环 位运算解法
    sublime搜索和替换--正则
    quarze的工作原理
    CF437D(The Child and Zoo)最小生成树
    HDU2504 又见GCD
  • 原文地址:https://www.cnblogs.com/lodor/p/6646875.html
Copyright © 2020-2023  润新知