Shared (static/global) attributes
I am in need of creating an attribute whose value is shared among all the instances of the same class.
To this end, next to my class pointer, I declare a global variable to hold the attribute value:
t_class *s_myobj_class; // whatever... long s_myattr_val;
In main I write the following code:
STATIC_ATTR_LONG(c, "attrname", ATTR_FLAGS_NONE, s_myattr_val);
This works to some extent, meaning that I do see the newly created attribute in the object’s inspector and the attribute’s value is indeed shared by all instances of the class. The problem is that the value is not assigned to my global variable (
s_myattr_val), and I don’t know where the value that Max references is. Needless to say, I cannot retrieve it to use it in my code.
I am using the STATIC_ATTR_LONG macro to create the attribute as it’s suggested by the API, however (and here might very well be my mistake) the ext_obex_utils.h file says that the attribute value should be passed as "Pointer to the value".
I tried declaring my attribute as such:
and even this:
long s_myattr_val; STATIC_ATTR_LONG(c, "attrname", ATTR_FLAGS_NONE, &s_myattr_val);
but the behavior is the same.
I am compiling on Xcode 4.3, Max 6.0.4 SDK.
Thanks for any insight.
without trying it out, just an idea. Did you try this?
long s_myattr_val; // Blah.... blah.... blah.... STATIC_ATTR_LONG(c, "attrname", ATTR_FLAGS_NONE, &s_myattr_val);
I’m not sure it would work, but maybe yes…
If you had read my post until the end you would know I did try that, but to no success…
Thanks for the suggestion anyway.
Sorry. My eyes somehow messed up your last line with the
long* declaration before it…
A search of all our source code indicates that the STATIC_ATTR_* macros are not used anywhere in Max. While this is further researched I’d recommend that you use a custom setter and getter for the attribute.
Yes, using a custom getter and setter ought to do the trick, however – after further investigation – I did manage to solve the issue in a slightly different manner. It just so happens that if you use
object_attr_setlong() to get/set the value of the attribute everything works as expected.
This tells me that Max already stores the global value somewhere internally without needing to be supplied one.
So without using any STATIC_ATTR_ macro I am creating the attribute as follows:
t_object *attr; attr = attribute_new("attrname", _sym_long, ATTR_FLAGS_NONE, (method)0L, (method)0L); class_addattr(c, attr);
in order to set and retrieve the attribute’s value:
long attrval; object_attr_setlong(x, gensym("attrname"), 74); attrval = object_attr_getlong(x, gensym("attrname"));
This makes sense thinking that attributes work by calculating memory offsets into the object’s data structure.
As far as I know, it is impossible to calculate an address offset for variables globally/statically declared because there’s no reference struct.
Forums > Dev