'Binding' Function Pointers on Load - c

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.

Related

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.

Struct Pointers in C

typedef struct data * Data;
I have something like this that I don't understand. I have some function later on that returns Data. What I don't get is, data * Data seems to me like a "empty" struct .. It doesn't have anything in it.
So what do I create when I do something like Data d; and what do I returns from function if this struct is empty?
Thank you.
That line of code is creating a type alias. It means that Data is an alias for the type struct data *. So, whenever you see Data, it's as if you saw a pointer to struct data.
When you do something like Data d;, you're basically declaring a pointer to struct data. You're not initializing the pointer, so it doesn't point to a valid struct data. Dereferencing the pointer will thus be invalid.
When you have a variable of type Data, you need to point it to somewhere valid before trying to dereference it.
Perhaps a less confusing approach would have been to do it like this instead:
typedef struct data *Data_ptr;
Which at least would convey the idea that Data_ptr is a pointer type alias.
You are looking at an opaque pointer.
Which means that the structure details are hidden to you, but the library functions that are using it are aware of the true content of the struct.
This type of declaration is usually made in public header files, while more private implementation use a complete declaration of the struct.

How can this object reference itself

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.

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).

Function with variable number of args in C and a design-oriented question

I have a C function named SetParams(...) with a variable number of arguments. This function sets up a static data structure (let us name it Data). SetParams is used with pairs of arguments, e.g. SetParams("paramA", paramA_value, "paramB", paramB_value) etc. It can also be called many times, e.g.
SetParams("paramA", paramA_value);
SetParams("paramB", paramB_value);
...
When all 'parameters' have been set, another function is called (let us name it Execute) that takes no args:
Execute();
// uses data from static 'Data' and performs error_handling and execution
I was wondering if I could structure this kind of code in a more object-oriented way. So, I would like some advice, especially for error-handling, since some pairs of args may contradict others.
The general practice for creating an object oriented design in C is for every method you have you will pass in a reference to a struct which is used to store all the classes member variables. In otherwords in C++ where you'd have listObj.clear() you have in C list_clear(&listObj).
This is kind of ugly, but it's necessary unless you want to use static member variables and limit the implementation to being used only once.
In the example below, notice how in each method a reference to a struct ParamUtilObj is passed in.
// --- paramUtil.h
// Stores all the objects member variables (public and private)
struct ParamUtilObj {
int paramCnt;
char param1[25];
char param2[25];
...
};
bool paramUtil_initialize( struct* ParamUtilObj pData );
bool paramUtil_addParam( struct* ParamUtilObj pData, const char* pKey, const char* pValue );
bool paramUtil_execute( struct* ParamUtilObj pData);
With respect to variadic methods. I'd try to avoid them if possible and just add them in one at a time. The business logic to validate the params is an entirely different topic in my opinion. I'd need more info to recommend the best approach. But... It seems to me since you're going to have to do validation such as if( MethodA ) then check for presence of some other argument... it might be easier to create several SetParam methods for each MethodType which the user could specify in the script.
I would recommend using a linked list to store your params and put all your methods as function pointers to a struct.
struct MyClass {
struct LinkedList* params;
void (*setParams)(...);
void (*execute)()
}
the linked list would be a key value pair
struct LinkedList {
struct LinkedList *next;
char * key;
char * value;
}
I dont know how you have your SetParams implemented, from the sound it just does a little bit of parsing and storing and forwards error handling downstream to the Execute call.
Since you are using variable length arguments, are you using the va_* macros? Doing so with a format string might allow you to insert the error handling into your SetParams call and allow Execute to just iterate over the values and do its thing.
Generally, if you have a function that handles setting parameters that should be where you manage errors associated with setting parameters. Errors encountered in the execution of command should be addressed in the execute function.
You cannot do it this way, because in C variadic functions don't know the number of arguments you've supplied, so you need somehow let function know it, like specifying number of params as first parameter or use printf way, when number of parameters can be found from format string.

Resources