I have a requirement for an OBJECT to be used by other objects. The requirement is that the OBJECT not require initialization by any external call. So I began with something like so...
// .h
struct My_Shared_Obj {
bool is_happy;
struct foo *foos;
};
typedef struct My_Shared_Obj *mysharedobj;
// .c
static mysharedobj MSO = NULL;
mysharedobj __instance();
void __mso_do_something();
void __mso_do_something() {
mysharedobj _mso = __instance();
// now do something with struct members
}
mysharedobj __instance() {
if(MSO == NULL) {
// initialize MSO
}
return MSO;
}
// we have an 'API' as follows
const struct MSO_API API = {
.do_something = &__mso_do_something
};
- Is this the best way to implement a self-initializing object?
- Reference behavior doesn't seem to make changes to
MSObut only for the scope of the function
Additionally, there are functions within this same source that are only accessible through the API ... ex:
static mysharedobj MSO = NULL;
/*
This method makes an assumption that since it can ever only be called by an API function
that the __instance() function has been invoked and that MSO will be a valid object.
*/
void __foo_add(foo *ptr) {
// assume we have next incrementing somewhere
MSO->foos[next] = *ptr;
}
void __mso_do_something() {
struct My_Shared_Obj _mso = __instance();
// hypothetical condition; assume we have a function that provides a foo for us...
if (!_mso->is_happy) {
__foo_add(get_a_foo());
_mso->is_happy = true;
}
}
I'm having difficulty getting the MSO object to be correctly referenced. The examples above are not contrived. It is what I have tried (names have been changed to protect the innocent). I have been experimenting with this for a bit now and not getting the results I need.
EDIT:
Corrected some typos. For what it's worth, the work I'm doing is not concerned with constraints of ISO standards. Thanks for the considerations, though.
mysharedobj *__instance()butmysharedobjis already a pointer.