TIP 605: Function to get class name from object

Login
Bounty program for improvements to Tcl and certain Tcl packages.
Author:         René Zaumseil <[email protected]>
State:          Draft
Type:           Project
Created:        15-Jul-2021
Post-History:   
Keywords:       Tcl
Tcl-Version:    8.7

Abstract

This TIP intends to add the following public function to Tcl:

Tcl_Obj * Tcl_GetObjectClassName(Tcl_Interp * interp, Tcl_Object object)

Rationale

There is currently a public function Tcl_GetObjectName to get the object name of an given Tcl_Obj. A similar function to get the class name does currently not exist. But these information is already existing in the internals of an oo object.

C Implementation

Tcl_Obj *
Tcl_GetObjectClassName(
    Tcl_Interp * interp,
    Tcl_Object object)
{
    Tcl_Object classPtr;
    classPtr = (Tcl_Object)(((Object *)object)->selfCls->thisPtr);
    if (classPtr == NULL) return NULL;

    return Tcl_GetObjectName(interp, classPtr);
}

Alternatives

The following alternative was posted by Donal Fellows on tcl-core:

I’d prefer getting the class to getting the name of the class (the name can be navigated to from there cheaply) as that makes the expensive failure-possible operations be something you can more commonly avoid, but otherwise this seems fine. We could have the name lookup you propose as well. This appears to be an area where I simply didn’t think about putting in any API.

The operation that I’m looking for is (probably; this is written from memory and I’ve not checked if it compiles):

    Tcl_Class Tcl_GetClassOfObject(Tcl_Object object) {
        return (Tcl_Class)(((Object *)object)->selfCls);
    }

Technically, the traversing of the thisPtr link is possible via Tcl_GetClassAsObject() and getting the name is the standard op. It’s the selfCls link that’s currently not exposed in the C API at all.

Documentation

The following documentation will be added in the Tcl_GetObjectName man page:

The function Tcl_GetObjectClassName will return the class name of an existing object. If the given object is not an class NULL is returned.

Copyright

This document has been placed in the public domain.