Next: , Up: Classes   [Index]


Object

Object Class

Ctalk defines the Object class by default at run time. All other classes are subclasses of Object.

Instance Variables

value

The value of the object. For classes that correspond to the C data types: Character, Float, Integer, LongInteger, and String, ctalk formats the value as it would appear as if output by the C printf function.

When you use one of these classes in a C expression, ctalk translates the object’s value to its C data type.

Other classes may define value to return class specific data.

Null Objects

To help make Ctalk compatible with C, Ctalk defines the macro STR_IS_NULL, which checks whether the object’s value evaluates to false in C. That means that objects that have the value ‘(null)’, are an empty string, or if the object’s value is a NULL pointer, all evaluate similarly. The STR_IS_NULL macro is defined in the include file ctalkdefs.h, so to use it, add the following line at the start of a class library.


#include <ctalk/ctalkdefs.h>

Ctalk also assigns an object the value of ‘(null)’ when an object is created or when Ctalk encounters a C NULL in an expression (which is a macro that expands to ‘((void *)0)’).

Instance Methods

! (void)

Overloads the ‘!’ prefix operator.

!= (Object arg)

Returns a Boolean value of False if the receiver and the argument are the same object, True otherwise. Also returns False if the receiver and argument’s values both evaluate to False.

& (void)

When used to overload C’s “address of” (‘&’) operator, is synonymous with the addressOf method, below.

-> (String member_name)

Given the name of an a C OBJECT * member name, like __o_name, __o_classname, __o_class and so on, return a String, Integer, or Symbol with the value of that member. See OBJECT typedef.

The class of the returned object depends on which OBJECT * is selected. Some of the results are returned as references contained in Symbol objects, which avoids unexpectedly changing the target object.

OBJECT Member        Expression                  Class of Result Object
-------------        ----------                  ----------------------
__o_name             obj -> __o_name             String
__o_classname        obj -> __o_classname        String
__o_superclassname   obj -> __o_superclassname   String
__o_value            obj -> __o_value            String
__o_class            obj -> __o_class            <obj's> class
__o_superclass       obj -> __o_superclass       <obj's> superclass
instancevars         obj -> instancevars         Symbol 
classvars            obj -> classvars            <obj's> class
__o_p_obj            obj -> __o_p_obj            <obj's> parent's class
scope                obj -> scope                Integer
attrs                obj -> attrs                Integer
nrefs                obj -> nrefs                Integer

The method sets the OBJECT_IS_DEREF_RESULT attribute on objects that the method creates.

The result of retrieving an object’s instance or class variables depends on the object. If the object is not a class object, then the classvars member will be NULL. The class of an instance variable is the parent object, so the Ctalk library returns the address of the first instance variable. If you want to check each variable, it is much easier to use the methods mapInstanceVariables or mapClassVariables, below.

Examples


/* Set a Symbol object and an Object instance to
   another object's class, and display the classes'
   name. */
int main () {

  String new myObject;
  Symbol new optr;
  Object new classObj;
  
  myObject = "String"; /*Needed by classObject, below.*/

  printf ("%p\n", myObject -> __o_class);
  printf ("%s\n", myObject -> __o_class -> __o_name);

  *optr = myObject -> __o_class;
  printf ("%p\n", (*optr) -> __o_class);
  printf ("%s\n", (*optr) -> __o_class -> __o_name);

  classObj = (*optr) classObject;
  printf ("%p\n", classObj);
  printf ("%s\n", classObj -> __o_name);

  classObj = myObject classObject;
  printf ("%p\n", classObj);
  printf ("%s\n", classObj -> __o_name);

}

/* To print an object's value. */
int main () {

  String new s;
 
  s = "StringValue";
 
  printf ("%s\n", s -> __o_value);

}

/* To save an object's scope to an Integer object, and
   print them. */
int main () {

  String new s;
  Integer new scopeInt;
  

  scopeInt = s -> scope;

  printf ("%d == %d\n", s -> scope, scopeInt);

}


/* To save an object's attributes to an Integer and
   print them. */

int main () {

  Integer new attrsInt;
  List new l;
  String new member1;
  String new member2;
  

  l = member1, member2;

  /* Check for an OBJECT_IS_MEMBER_OF_PARENT_COLLECTION attribute
     (currently its definition is (1 << 7), or 128), which is set
     in each of the list's Key objects. (The '->' operator in the
     expressions has a higher precedence than '*', so parentheses
     are necessary.) */
  attrsInt = (*l) -> attrs;

  printf ("%d == %d\n", (*l) -> attrs, attrsInt);
}


Note: The use of __o_classname and __o_superclassname as separate object member is being superceded by the CLASSNAME and SUPERCLASSNAME definitions. The -> method recognizes both the old and new names, but if -> is used with an OBJECT * as a C operator, then the program must use the CLASSNAME or SUPERCLASSNAME macros. See CLASSNAMEMacro.

= (Object new_object)

A basic assignment method. Assigns new_object so that the receiver label can refer to it.

== (Object arg)

Returns a Boolean value of True if the receiver and the argument are the same object, False otherwise.

As a special case, the method returns True if the receiver and argument’s values evaluate to a C NULL. Refer to the description of null objects above. See NullObjects.

addInstanceVariable (char *name, OBJECT *value)

Add instance variable name with value to the receiver.

addressOf (void)

Return a Symbol that contains the address of the receiver. This method is functionally equivalent to the C language ‘&’ operator.

asFloat (void)

Return a Float object with the value of the receiver.

asString (void)

Return a String object of the receiver.

asSymbol (void)

If the value of the receiver is an object reference, return a Symbol object with that reference. Otherwise, return a Symbol object with a reference to the receiver.

backgroundMethodObjectMessage (Method method_object)

Send the message defined in method_object to the receiver as a new process, which runs concurrently until method_object returns.

The argument, method_object, is a previously defined method which takes no arguments. The return value, if any is not saved when the background process exits.

Here is a brief example that opens an ObjectInspector on a process.


Object instanceMethod bgMethod (void) {
  self inspect "bgMethod> ";
  printf ("bgMethod printed this.\n");
}

int main () {
  Integer new i;
  Method new bgMethodObject;
  int status;

  bgMethodObject definedInstanceMethod "Object", "bgMethod";
  i backgroundMethodObjectMessage bgMethodObject;

  wait (&status);  /* Returns when the background */
                   /* process exits.              */

}

basicNew (char *name)
basicNew (char *name, char *value_expr)
basicNew (char *name, char *classname, char *superclassname, char *value_expr)

If given with one argument, the receiver must be a class object, and the method creates a new object with the name given as the argument and a value of ‘(null)’.

With two arguments, create a new object with the name and value given in the arguments, and with the class and superclass of the receiver, which needs to be a class object in this case also.

If the method is used with four arguments, create a new object with the name, class, superclass and value given by the arguments - in this case, basicNew doesn’t use the class and superclass of the receiver.

In each case, the newly created object contains all of the instance variables defined by the class object and has a scope of LOCAL_VAR|METHOD_USER_OBJECT and a reference count of 1.

Note: The addition of the receiver’s instance variables means you need to be careful when the receiver is not a class object. The basicNew method does not check for cascading or circular instance variables. So if you’re creating and then pushing a lot of items, make sure the method’s receiver is a class object, and assigning the new object using a Symbol is more robust that assigning other types of objects.

That is, a set of statements like


*tokSym = String basicNew "token", valuebuf;
myList push *tokSym;

is much more reliable than, say


myTok = myString basicNew "token", valuebuf;
myList push myTok;

become (OBJECT *original_object)

Make the receiver a duplicate of the argument object.

callStackTrace (void)

Print a call stack trace.

class (char *classname)

Declare a new class classname. The class declaration consists of a superclass name, the class keyword, the name of the new class, and an optional documentation string. For example;


FileStream new WriteFileStream;

... or, with a docstring between the class name and semicolon ...

FileStream new WriteFileStream
"Defines the methods and instance variables that write data to files. Also
defines the class variables stdoutStream and stderrStream, which are the 
object representation of the standard output and standard error streams.";

className (void)

Return a String object containing the class name of the receiver.

classObject (void)

Return the class object named by the receiver’s value. Normally the receiver should be a String object - the method uses the C value of the receiver to retrieve the class object by its name. If the receiver is a class object, the method returns the receiver itself.

copy (Object source_object)

Copy source_object to the receiver. This method replaces the receiver, which received the message, with a completely new copy of the source_object argument. The original receiver object no longer exists.

decReferenceCount (void)

Decrease the receiver object’s reference count by one.

delete (void)

Delete the receiver object and its instance variables.

For some of the details of how Ctalk deletes objects, refer to the __ctalkDeleteObject () API function. See __ctalkDeleteObject.

disableExceptionTrace (void)

Disable method walkback displays when handling exceptions.

docDir (void)

Returns a String that contains the path where the Ctalk-specific documentation is installed on the system (i.e., documentation other than man pages and Texinfo manuals).

dump (void)

Create an ObjectInspector object and print the object’s contents on the terminal. This is a convenience method for the ObjectInspector : formatObject method.

enableExceptionTrace (void)

Enable method walkback displays when handling exceptions.

getReferenceCount (void)

Return an Integer with the receiver’s reference count.

hasPointerContext (void)

Returns a Boolean value of True if the receiver appears in a pointer context; i.e., on the left-hand side of an assignment operator in an expression with some dereferencing method (usually a “*”), as in this example.


Symbol new myNewObjectPtr;
Symbol new myOldObjectPtr;


*myNewObjectPtr = myOldObjectPtr;

incReferenceCount (void)

Increase the receiver object’s reference count by one.

inspect (void)
inspect (String promptStr)

Open an inspector on the receiver object. At the prompt, typing ‘?’ or ‘help’ displays a list of the inspector’s commands. If given a String object as its argument, displays the string as the inspector’s command prompt. This method is a shortcut for inspect in ObjectInspector class. See ObjectInspector_inspect.

is (char *className)

Return TRUE if the receiver is a member of the class given in the argument, FALSE otherwise. Note: Don’t use an expression like, ‘obj is Class’. The argument must be a valid, defined class, which simplifies the method considerably.

To determine if an object is a class object, use isClassObject, which is mentioned below. This example illustrates the difference.


if (myObject is String) {   /* OK - String is a defined class. */
 ...
}

if (myObject is Class) {    /* Not OK - 'Class' is not a defined class. */
 ...
}

if (myObject isClassObject) {  /* OK - Just check whether the object is
 ...                              its own class object. */
}

isClassMethod (char *classMethodName)

Return TRUE if the receiver’s class defines an instance method named classMethodName, FALSE otherwise. If the receiver is an instance or class variable, look for the method in the class of the receiver’s value.

isClassObject (void)

Returns a Boolean value of True if the receiver is a class object, False otherwise.

isInstanceMethod (char *instanceMethodName)

Return TRUE if the receiver’s class defines an instance method named instanceMethodName, FALSE otherwise. If the receiver is an instance or class variable, look for the method in the class of the receiver’s value.

isInstanceVariable (char *instanceVariableName)

Return TRUE if the receiver has an instance variable named instanceVariableName, FALSE otherwise.

instanceMethod (char *alias, char *name, (args)

Declare a method of the receiver’s class with the name name, with the arguments args, and, optionally, with the alias alias. See Methods.

isNull (void)

Return TRUE if the receiver is a null result object, FALSE otherwise.

isNullValue (void)

Return TRUE if the receiver’s value is NULL, ‘(null)’, or ‘0’, FALSE otherwise. Note that this method is here for compatibility with older programs. New programs should not need it.

isSubClassOf (String classname)

Returns True if the reciever’s is a member of classname or one of its subclasses, False otherwise.

libraryPath (void)

Return the file path name of the receiver’s class library.

mapClassVariables (OBJECT *(*fn)())

Apply the argument, fn to each of the class variables in the receiver’s class object. The argument may be either a method or a code block. Refer to the Ctalk Tutorial for examples of inline method messages using methods like map and mapInstanceVariables.

mapInstanceVariables (OBJECT *(*fn)())

Apply the argument, fn, to each of an object’s instance variables. The argument may be either a method or a code block. Refer to the Ctalk Tutorial for examples of inline method messages using methods like map and mapInstanceVariables.

methodObjectMessage (Method method_object)
methodObjectMessage (Method method_object, Object arg1, Object arg2)

Perform a method call with a Method class object. The method_object argument and its own arguments must have been previously defined. See Method.

methodPoolMax (void)
methodPoolMax (Integer new_max_size)

Set (with one argument) and retrieve (with no arguments) the maximum number of objects in each method’s object pool. When a method’s pool size reaches this number of objects, the pool deletes the the oldest object in the pool to make room for the new object.

Generally, the default pool size is suitable for the language tools and demonstration programs that come packaged with Ctalk. Some of the test programs in the test/expect subdirectory that run through many iterations (i.e., thousands of iterations) require a larger pool size. This is especially true if a program uses many C variables when iterating through its operations, and whether the C variables are simply scalar or constant values (e.g., ints, doubles, and literal strings), and whether the variables are pointers to objects in memory.

The default maximum pool size is set when the Ctalk library is built. This size is reported in the configure status report during the build process.

methodObjectMessage (Method methodObject)
methodObjectMessage (Method methodObject, Object arg1, Object arg2)

With three arguments, the method uses the second and third arguments as the method instance’s arguments, without previous calls to the withArg method (defined in Method class).

Method instances with two arguments are commonly used in graphical event dispatchers. They’re found mostly in X11PaneDispatcher class, and the three-parameter form of methodObjectMessage allows the method instance calls to be more efficient.

The following examples of method calls shows how to call method instances with and without using the withArg method first.

This example is from X11PaneDispatcher class.


  /* This example pushes the arguments separately. */
__subPane handleKbdInput withArg __subPane;
__subPane handleKbdInput withArg __event;
__subPane methodObjectMessage __subPane handleKbdInput;

  /* The three-argument form of methodObjectMessage allows
     passing two arguments to a method instance with only
     a single expression. */
__subPane methodObjectMessage __subPane handleKbdInput,
  __subPane, __event;

This example is the demos/ipc/sockproc.c demonstration program, which shows how to define and start a method instance as a separate process.


#define SOCK_BASENAME "testsocket.$$"

String new gSocketPath; /* The socket path is common to both
			   processes. */

Object instanceMethod startTimeServer (void) {
  UNIXNetworkStreamReader new reader;
  String new utcTimeString;
  CalendarTime new timeNow;
  SystemErrnoException new ex;

  reader openOn gSocketPath;
  if (ex pending) {
    ex handle;
    return ERROR;
  }

  while (1) {
    utcTimeString = reader sockRead;
    if (ex pending) {
      ex handle;
      return ERROR;
    }
    if (utcTimeString length > 0) {
      timeNow = utcTimeString asInteger;
      timeNow localTime;
      printf ("%s\n", timeNow cTimeString);
    }
  }
}

int main (int argc, char **argv) {

  CTime new thisTime;
  CTime new prevTime;
  UNIXNetworkStream new strObject;
  UNIXNetworkStreamWriter new client;
  Method new timeServerInit;
  Integer new childPID;
  SystemErrnoException new ex;
  Object new procRcvr;

  gSocketPath = strObject makeSocketPath SOCK_BASENAME;

  timeServerInit definedInstanceMethod "Object", 
    "startTimeServer";
  childPID = 
    procRcvr backgroundMethodObjectMessage timeServerInit;

  sleep (1); /* Wait a sec while the reader process creates the
		socket. This interval might be system dependent. */

  client openOn gSocketPath;
  if (ex pending) {
    ex handle;
    return ERROR;
  }

  prevTime utcTime;

  while (1) {

    thisTime utcTime;

    if (thisTime != prevTime) {

      client sockWrite (thisTime asString);

      if (ex pending) {
	ex handle;
	return ERROR;
      }
      
      prevTime = thisTime;

    }
    usleep (1000);
  }
  exit (0);
}

methods (Boolean findClassMethods)

Return a string containing the methods defined by the receiver’s class, one method per line. If findClassMethods is True, return a list of class methods in the class. If the argument is False, return a list of the class’s instance methods.

name (void)

Return the name of the receiver as a String object.

new (newObject1, newObject2, newObject3...)

Create an object or object’s of the receiver’s class with the names newObject1, etc. For example:


String new myString1, myString2, myString3;

printSelfBasic (void)

Print the contents of the receiver to the program’s standard error output.

setReferenceCount (Integer refCnt)

Set the receiver’s reference count to the value given as the argument. Note, however, that the reference count given as the argument does not include any changes in the reference count as this method is executed. If you’re unsure about how to adjust the reference count it’s safer to use incReferenceCount and decReferenceCount instead, or use the __objRefCntSet () library function directly. See objRefCntSet.

sizeof (Object)

Overloads the C sizeof operator when the argument is an object. If the argument is a C variable or a type expression, then Ctalk uses the compiler’s sizeof operator.

superclassName (void)

Return a String that contains the name of the object’s superclass, or ‘(null)’ if the receiver is an instance of Object class, which has no superclass.

traceEnabled (void)

Return TRUE if exception walkback displays are enabled, FALSE otherwise.

value (void)

Returns the value of the receiver object. When you use an object without a method, ctalk uses the value message to return the object’s value. For example,

  printf ("%s", stringObject);

is the same as,

  printf ("%s", stringObject value);

Next: , Up: Classes   [Index]