How can this object reference itself - c

I've been tinkering with some code in a effort to understand OOP using c.
I really like this style and want to use it. The code sample works great if another class creates an instance of FooOBJ.
How can FooOBJ reference itself to change its own variables?
Do I need to make a copy of foo in the constructor or something like that or am I wandering away from the right way to use this methodology?
struct fooobj {
int privateint;
char *privateString;
};
FooOBJ newFooOBJ(){
FooOBJ foo=(FooOBJ)malloc(sizeof(struct fooobj));
bzero(foo, sizeof(struct fooobj));
return foo;
}
void setFooNumber(FooOBJ foo,int num){
if(foo==NULL) return; /* you may chose to debugprint something
*instead
*/
foo->privateint=num;
}
void setmyself(int val)
{
//this->privateint = val
}

Well, any function operating on an instance of your "class" will have to take a pointer to the instance. This happens automatically and implicitly in C++, but in C you'll have to pass a "this" pointer everywhere.
What this means is that your setFooNumber has the right signature for a "member function", whereas setmyself does not.

There's a reason C++ and other OO languages have an implicit parameter to instance methods. The only way this can be done is if you explicitly pass a this pointer. A function doesn't have access to something that isn't declared in an appropriate scope: locally or globally (parameters being local).
To understand OOP in C, you'll need to understand how to simulate pure OO code in a procedural way.

Related

Returning a pointer to a global static struct object in C

typedef struct
{
int age;
int number;
} person;
static person self;//global declaration
person *Self(){
return &self;
}
I have been trying to understand the above similiar code which is used in a large code base any help would be appreciated.
Why do we need such kind of function like above Self() function in C ?
What are the benefits ?
Is there any drawbacks ?
This specific snippet doesn't make much sense.
static can be used as "poor man's private encapsulation", if an object is guaranteed to be a "singleton" - that is, only one instance exists and it is not accessed by multiple threads.
In this case the scope of the variable is reduced to the local .c file by static.
And Self acts as a "getter" function. (As a singleton in a multi-threaded environment, you could place mutex/semaphores in the setter/getter functions, so that would be another use for them.)
However, while such a design might make sense in some cases, returning a non-const qualifier pointer to a private variable is just as bad design as skipping private encapsulation and using globals/file scope variables.
To answer your questions based on the above:
Why do we need such kind of function like above Self() function in C ?
If it returned a const qualified pointer then it could make sense as a getter function. As it stands, it's just bloat and bad design though.
What are the benefits ?
Is there any drawbacks ?
As the code stands, no benefits, only drawbacks. It looks like a botched attempt to achieve private encapsulation.
To do proper, multi-instance private encapsulation in C, you wouldn't use static but so-called "opaque types". Here is an example: How to do private encapsulation in C?
This a way to have a global variable without using an actual global variable. This is certainly a pattern to avoid because now you can change the value of the struct from anywhere is this can lead to various bug hard to detect.
A cleaner way would be to return a copy of the struct or a pointer on a const variable to avoid being able to modify the variable from outside the module. If you need to modify the struct, create set/reset functions.
person Copy_of_self() {
return self;
}
const person *Self() {
return (const person *)&self;
}
void Set_self(int age, int number) {
// Here you could add some checking on input values
self.age = age;
self.number = number;
}

Does C have a version of JavaScript "this"?

I've use quite a bit of JavaScript so far. If you were to use an object constructor in JavaScript, you have access to the this constructor.
So my question relates to trying to use a similar concept in C. I created a struct that I want to be able to self reference:
struct Storage {
void (*delete)();
}
So if I were to allocate a Storage class:
struct Storage *myStruct = malloc(sizeof(struct Storage));
Let's say I'm trying to delete myStruct. If I have some delete function that I point to (with myStruct->delete = deleteStructure), I would like to do something like this:
myStruct.delete();
which would then free() the struct through a self referencing variable inside of said delete function. I'm wondering if there would be a way to have the delete function look like:
void deleteStructure() {
free( /* "this" or some equivalent C self-reference */ );
}
My assumption from research so far is that this is not possible since this is usually only in object oriented programming languages. If this is not possible, I'm wondering what would be the semantically correct way to do this. I'm hoping to make the usage of this delete functionality rather simplistic from a user interface perspective. The only way I understand this to work would be passing a reference to the structure like:
void deleteStructure(struct Storage *someStructure) {
free(someStructure);
}
which would then require deletion to be done as follows:
deleteStructure(myStruct);
To sum up: is there a way to make a delete function that uses self references in C, and if not, what would be the most semantically correct way to delete a structure in the most user friendly way?
No. You cannot even define a function for a struct.
struct Storage {
void (*delete)();
}
simply stores a pointer to a void function. That could be any void function and when it is being called, it has no connection to Storage whatsoever.
Also note that in your code, every instance of the struct stores one pointer to a void function. You could initialize them so that they all point to the same function, in which case you would simply waste 64 bit per instance without any real benefit. You could also make them point to completely different functions with different semantics.
As per #UnholySheep's comment, the correct semantical use of a struct with connection to a C function will follow the structure:
struct Storage {
/* Some definitions here */
}
void deleteStructure(struct Storage *someStructure) {
free( /* all inner structure allocations */ );
free(someStructure);
}
Here's more about passing structs by reference.

Exposing only void pointers in an API

I've seen a good deal of C libraries that do not present the objects they deal with internally as distinct types, but instead wrap them with void pointers before letting you access them. In practice, the "private" source files look something like:
typedef struct {
int value;
} object;
void * object_new(void)
{
object *o = malloc(sizeof(object));
o->value = 1;
return o;
}
int object_get(void *o)
{
return (object *)o->value;
}
void * object_free(void *o)
{
free(o);
}
And in the main header you have only:
void * object_new(void);
int object_get(void *o);
void * object_free(void *o);
Now I wonder: is there a particular reason they do so? If the idea is to ensure the API user has no access to the internals of the object, isn't it sufficient to only expose the type name in the main library header, and to hide the details of the underlying structure (or whatever be the actual object) in the implementation files?
The reason to hide the types behind void pointers could be a (misguided) attempt to hide (in the sense of modular programming) the internal details. This is dangerous, as it throws any type checking the compiler might do right out the window.
Better would be something along the lines:
for-user.h:
struct internalstuff;
void somefunc(struct internalstuff *p);
for-internal-use.h:
#include "for-user.h"
struct internalstuff { ...};
implementation.c:
#include "for-internal-use.h";
void somefunc(struct internalstuff *p)
{
...
}
This way nobody will mix up internalstuff with a random string or the raw result from malloc(3) without getting at least a warning. As long as you only mention pointers to struct internalstuff in C it is fine not to have the definition of the struct at hand.
Something along the same lines can be done in C++ with class, and I'd be suprised if Objective C doesn't allow the same. But the object oriented programming languages have their own, much more flexible, tools for this. There you can define a bare-bones base class to export, while internally extensions are used. Take a look at a good C++ book for details (there are extensive lists here).
In a world of objects (Obj-C and C++), I believe the reason is mostly to do with inheritance. If a subclass is created from the base class, then there is no problem with the type of the return value when creating a new instance of the class. With just straight C, there does not appear to be a clear cut reason as no internal details are revealed or dependencies created.
You're correct.. the idea in most of these cases is to restrict the API user from the internals of the object. The decision about type names though really is just a matter of style. If you were to expose the type name in the header as you suggest (which some APIs do), it would probably look something like:
typedef void* object;
There is no real advantage or disadvantage to doing this from the compiler's point of view. Although it does give the API user a better understanding of what's going on:
object object_new(void);
int object_get(object o);
void object_free(object o);

'Binding' Function Pointers on Load

So I've been tinkering around with object orientism in C by making a simple little stack using a 'class' struct and a typedef'd 'instance' struct. The class struct is simply full of function pointers that operate on pointers to instance structs. When I first went about it, I said to myself "I'll just bind the pointers when I initialize the instance struct!" You might guess that this didn't work, since my initialization function was actually a pointer that still had not been assigned a value yet.
(it's currently almost 5AM - closer to wakeup time than bedtime)
So, I am asking if there is any way to effectively bind the function pointers of the at runtime such that I don't need to explicitly call a function that binds them - I was thinking maybe some sort of counterpart to atexit.
If the 'class' struct is always the same, you can initialise it statically:
void do_x_to_instance(instance *);
struct class_type {
void (*do_x)(instance *);
...
} myclass = {
&do_x_to_instance,
...
};
This is how the Python C API works to define extension types, for example.

Wrapping a C Library with Objective-C - Function Pointers

I'm writing a wrapper around a C library in Objective-C. The library allows me to register callback functions when certain events occur.
The register_callback_handler() function takes a function pointer as one of the parameters.
My question to you gurus of programming is this: How can I represent an Objective-C method call / selector as a function pointer?
Would NSInvocation be something useful in this situation or too high level?
Would I be better off just writing a C function that has the method call written inside it, and then pass the pointer to that function?
Any help would be great, thanks.
Does register_callback_handler() also take a (void*) context argument? Most callback APIs do.
If it does, then you could use NSInvocation quite easily. Or you could allocate a little struct that contains a reference to the object and selector and then cobble up your own call.
If it only takes a function pointer, then you are potentially hosed. You need something somewhere that uniquely identifies the context, even for pure C coding.
Given that your callback handler does have a context pointer, you are all set:
typedef struct {
id target;
SEL selector;
// you could put more stuff here if you wanted
id someContextualSensitiveThing;
} TrampolineData;
void trampoline(void *freedata) {
TrampolineData *trampData = freedata;
[trampData->target performSelector: trampData->selector withObject: trampData-> someContextualSensitiveThing];
}
...
TrampolineData *td = malloc(sizeof(TrampolineData));
... fill in the struct here ...
register_callback_handler(..., trampoline, td);
That is the general idea, anyway. If you need to deal with non-object typed arguments and/or callbacks, it gets a little bit trickier, but not that much. The easiest way is to call objc_msgSend() directly after typecasting it to a function pointer of the right type so the compiler generates the right call site (keeping in mind that you might need to use objc_msgSend_stret() for structure return types).

Resources