Search code examples
c++delphitransactionsequivalent

Help me translate the C++ code to Delphi


im having hardtime in memset and memcpy. can somebody trasnlate this for me, or suggestion on how this thing work?

do{
  memset(szSpeechBuf, 0x0, sizeof(char)*QSIZE);
  if((nBufIter+1)*QSIZE > nRawBufLen)
    {
      diff = nRawBufLen - (nBufIter)*QSIZE;

      if(diff < 0)
      {
        printf("DetectSpeech() error : timeout!!!");
        exit(1);
      }
      memcpy(szSpeechBuf, szRawBuf+(QSIZE*nBufIter), diff);
    }
  else
    memcpy(szSpeechBuf, szRawBuf+(QSIZE*nBufIter), sizeof(char)*QSIZE);
} while(1);

// where szSpeechBuf: PAnsiChar; nBufIter: Integer; Const QSIZE = 3200

Solution

    • memset fills a number of bytes with the specified value. In Delphi, we use FillChar for this. But if the value we want to fill with is zero, you can also use the ZeroMemory function.

    • memcpy copies a block of bytes from one location to another (in RAM). In Delphi, we use Move for this. You can also use CopyMemory (or the identical function MoveMemory) if you want to work with pointers instead of Delphi variables.

    That is,

    Move(a, b, n)
    

    copies n bytes from the data named a to the location of b, where a and b are variables. This is equivalent to

    CopyMemory(@b, @a, n)
    

    where @a and @b are the pointers to the source and destination, respectively. (Personally, I think the latter syntax is easier to explain, in some sense. It takes two addresses, and after all, that is how we work with memory.)

    Hence, if p and q are pointers, you can do

    CopyMemory(q, p, n)
    

    or

    Move(p^, q^, n).
    

    You might also want to know how to allocate, reallocate, and free memory on the heap in Delphi. You use the GetMem, ReallocMem, and FreeMem procedures, respectively.

    Working with pointers

    Deplhi can be rather restrictive when it comes to pointer arithmetics. But on a 32-bit system (such as the ones running Delphi applications), a pointer is really just a 32-bit unsigned integer, that is, a cardinal. So you can work with pointers just like cardinals, if you just tell the compiler to do so.

    Hence, if the compiler doesn't allow

    myPtr + 200
    

    then you can do

    cardinal(myPtr) + 200.