Version 3 of Tcl_NewByteArrayObj

Updated 2008-10-29 13:00:57 by Duoas

Tcl_Obj * Tcl_NewByteArrayObj(CONST unsigned char *bytes, int length)

Tcl_Obj * Tcl_NewByteArrayObj(bytes, length)

Tcl_NewByteArrayObj will create a new object of byte-array type. Both of these procedures set the object's type to be byte-array and set the object's internal representation to a copy of the array of bytes given by bytes. Tcl_NewByteArrayObj returns a pointer to a newly allocated object with a reference count of zero.

http://www.tcl.tk/man/tcl8.4/TclLib/ByteArrObj.htm


To populate a byte array by a C extension and return it as the result object, the following code might be used:

Tcl_Obj *pObj = Tcl_NewObj();
unsigned char *pChar = Tcl_SetByteArrayLength(pObj, 3);

// Dummy population functionality
pChar[0] = '\1'; pChar[1] = '\xff'; pChar[2] = '\x80';
Tcl_InvalidateStringRep(pObj);
Tcl_SetObjResult(interp,pObj); 

Remarks:

  • Tcl_NewObj() may be replaced by Tcl_NewByteArrayObj( NULL, 0 ).
  • If the object is not newly created (for example a parameter object is modified, one should check the object to be shared:
if ( Tcl_IsShared(pObj) )
    pObj = Tcl_DuplicateObj(pObj);

DKF: I don't recommend using a length of 0 to Tcl_NewByteArrayObj; the behaviour of that depends on whether malloc(0) keels over (which is system dependent).

Duoas That seems me fairly obnoxious. Doesn't the Tcl_NewByteArrayObj() code know that it oughtn't bother to try allocating zero bytes, and just initialize an empty/nil internal representation to begin with?