Archived Forum Post

Index of archived forum posts

Question:

CkByteData::borrowData not working?

Oct 21 '15 at 19:16

my CkByteData doesn't use the buffer passed in via borrowData. Here is my snippet:

CkByteData outBytes;
char testBuf[100000] = {0};
outBytes.borrowData(testBuf, sizeof(testBuf));
http.S3_DownloadBytes(s3Options.bucketName, objPath.c_str(), outBytes); // returns false for ranged get (as it returns 206, not 200)
if (outBytes.getSize() > 0) {
    std::cout << "TS3Bucket::testUpload, got " << outBytes.getSize() << std::endl;
    const unsigned char *test = outBytes.getData();
    std::cout << "test ->" << test <<  "<-" << std::endl;
    std::cout << "testBuf ->" << testBuf << "<-" << std::endl;
}

The output is:

TS3Bucket::testUpload, got 8192
test ->.shd<-
testBuf -><-
So clearly the call worked (the ".shd" is a signature), but isn't in testBuf. I've looked at various sample code and it seems all okay.


Answer

The borrowData method is for providing read-only data to the CkByteData object. In other words, it's not for providing a buffer that Chilkat will write into. It's for providing a buffer that contains data that Chilkat will read.

The borrowData method provides a means for passing bytes in a CkByteData without having to do a memory copy. If bytes are passed via borrowData, and then the CkByteData object is modified, such as by a Chilkat method, or by calling CkByteData::append to append more data, then internally a new buffer is allocated, the original borrowed data is copied to it, and the append happens on the new buffer.

The reason things work this way have to do with the ownership of the memory. The CkByteData manages an internal buffer that is automatically expanded as needed when data is appended. It owns the internal buffer -- and therefore may delete it and re-allocate to a larger internal buffer. If an app holds a pointer to the internal data owned by the CkByteData object, it should realize that the pointer may not be valid if the CkByteData is modified.

When borrowData is called, it provides a fixed-size buffer filled with data owned by the app that CkByteData cannot resize or deallocate. Borrow data is assuming the buffer you pass actually contains data. You're not passing buffer space with no data, but you're actually passing data. If you pass a 10-byte array to borrowData, then Chilkat is assuming it's a 10-byte buffer filled with 10 bytes of data.

So.. in summary, you can use borrowData for inputs to a Chilkat method, but not for outputs.