Values of member struct get lost after being passed to a function as a pointer - c

Summary:
I have an issue where my pointer inside a struct gets randomised after being passed to the function.
So I pass the original struct with the pointer being in-tact (I checked it there and it works), but after being passed to the function the stated pointer doesn't work anymore. The pointer points to the same address, but the content of the struct is lost and randomised without any prior data still existing.
Note: All of the signatures like ph_ReturnTypeInt are just specialised types aka. structs where I added additional data which don't matter much in this case, except for the function pointer signatures
Note 2: Since it's a lot of code that might be unimportant I tried to explain what is what, but here the GitHub link if you need it. Else thank you if you can help me ^^
The function being called:
/// Defined wrapper for the function
/// #param call_ctx Call Context for the wrapper
/// #param x Example for how a user argument could look like
ph_ReturnTypeInt DecorateFunc_Wrapper(DecorateFunc_WrapContext *call_ctx, int x)
{
printf("Called wrapper\n");
// ----> Compiler generated ---->
ph_ReturnTypeInt call_r;
// Child Context is null -> Reached lowest level of wrapping
if (!call_ctx->child_ctx && !call_ctx->has_child_ctx)
{
// Calling the wrapped function
call_r = call_ctx->wrapped_func(x);
}
else
{
// Passing the context down one level to the other function
call_r = (*call_ctx->child_ctx).wrapper_func(call_ctx->child_ctx, x);
}
int local_r = call_r.actual_value;
// <---- Compiler generated <----
printf("Finished function call\n");
// ----> Compiler generated ---->
ph_ReturnTypeInt func_r = {
.base.is_exception = false,
.base.is_null = false,
.actual_value = local_r
};
// <---- Compiler generated <----
return func_r;
}
The struct which "loses" its child_ctx pointer:
/// Context for the DecorateFunc Decorator. Contains a child_ctx element to point to a child if it exists. Contains
/// a wrapper function and wrapped function. The wrapped function should be NULL if child_ctx is populated.
typedef struct DecorateFunc_WrapContext {
bool has_child_ctx;
ph_DecoType_Int_Int wrapped_func;
DecorateFunc_Wrapper_Type wrapper_func;
DecorateFunc_WrapContext *child_ctx;
} DecorateFunc_WrapContext;
Function that returns the struct:
/// Decorates a function and returns a struct containing the func and the wrapper specified for this decorator.
/// #param passable Passable struct that can either contain a function or an initialised wrapped struct that should
/// be wrapped again. In both cases the types must match with the target of the decorator to correctly pass
/// the arguments.
DecorateFunc_WrapContext DecorateFunc(DecorateFunc_WrapContext ctx)
{
printf("Called decorator\n");
// ----> Compiler generated ---->
DecorateFunc_WrapContext new_ctx;
// Child Context is null -> Reached lowest level of wrapping / The function does not have any more wrapping
if (!ctx.child_ctx && !ctx.has_child_ctx && !ctx.wrapper_func)
{
new_ctx = (DecorateFunc_WrapContext) {
.has_child_ctx = false,
.wrapper_func = DecorateFunc_Wrapper,
.wrapped_func = ctx.wrapped_func,
.child_ctx = NULL
};
}
else
{
// Creating a new context and passing the context as a child
new_ctx = (DecorateFunc_WrapContext) {
.has_child_ctx = true,
.wrapper_func = DecorateFunc_Wrapper,
.child_ctx = &ctx,
};
}
// <---- Compiler generated <----
return new_ctx;
}
The main function:
int main()
{
DecorateFunc_WrapContext p;
p = (DecorateFunc_WrapContext) { .wrapped_func = &main_func };
DecorateFunc_WrapContext deco_ctx = DecorateFunc(p);
deco_ctx.wrapper_func(&deco_ctx, 15);
/* Wrapping the wrapped context */
DecorateFunc_WrapContext deco_ctx2 = DecorateFunc(deco_ctx);
deco_ctx2.wrapper_func(&deco_ctx2, 20);
}
The function passed as function pointer:
ph_ReturnTypeInt main_func(int x)
{
printf("Called decorated function - Passed argument: %i\n", x);
/* Compiler generated return */
ph_ReturnTypeInt r = {
.base.is_exception = false,
.base.is_null = false,
.actual_value = 3
};
return r;
}
And lastly the additional context (the main file and the other header with the signatures, which shouldn't have a big influence):
// Used content of the header. Other content is just declarations etc.
/* Undefined Base Return which serves as the base for all ReturnTypes */
typedef struct ph_UndefBaseReturn {
bool is_exception;
const char* exception;
const char* traceback;
bool is_null;
} ph_UndefBaseReturn;
/* Para-C Return of Type int. Compiler-Generated */
typedef struct ph_ReturnTypeInt {
ph_UndefBaseReturn base;
int actual_value;
} ph_ReturnTypeInt;
/* Decorator Return Types - Compiler-Generated */
typedef ph_ReturnTypeInt (*ph_DecoType_Int_Int)(int);
// At the top of the main file
typedef struct DecorateFunc_WrapContext DecorateFunc_WrapContext;
/// Signature of the wrapper - Returns int and contains as parameters a int return function and an int
/// This type will be automatically generated for any wrapper, but only used in the decorator for correctly creating
/// the struct which will store the wrapper and wrapped function.
typedef ph_ReturnTypeInt (*DecorateFunc_Wrapper_Type)(DecorateFunc_WrapContext*, int); // R: int - P: struct, int

In main:
/* Wrapping the wrapped context */
DecorateFunc_WrapContext deco_ctx2 = DecorateFunc(deco_ctx);
deco_ctx2.wrapper_func(&deco_ctx2, 20);
In DecorateFunc:
DecorateFunc_WrapContext DecorateFunc(DecorateFunc_WrapContext ctx)
{
...
{
// Creating a new context and passing the context as a child
new_ctx = (DecorateFunc_WrapContext) {
.has_child_ctx = true,
.wrapper_func = DecorateFunc_Wrapper,
.child_ctx = &ctx, // <-- this line
};
}
}
The assignment to child_ctx at <-- this line links new_ctx to a temporary copy of deco_ctx in main(). Since you passed the structure by value, the compiler constructed a temporary copy of it on the stack, then (likely) re-used that area of the stack once the function completed. Your link (.child_ctx) is now dangling.
You need to pass the addresss of new_ctx, adjust DecorateFunc to accept a pointer, assign .child_ctx to that pointer, and adjust your tests to deal with a pointer, it works.

Related

Why does my pointer doesn't want to be dereferenced?

Actually I am registering Callback to lower layer of code from upper layer.
So In a c "config file" file I have this :
typedef enum eActivationType
{
TYPE_A = 0,
TYPE_B,
TYPE_C,
}ActivationType_t;
typedef struct Callbacks_s
{
void (*OnJoin)(ActivationType_t Mode);
}NemeusCallbacks_t;
static Callbacks_t Callbacks = {
.OnJoin = OnJoin,
.//I have other callbacks here but I the first one works the other will work
};
static Params_t Params = {
.DefaultActivationType = TYPE_A,
//other params
}
Callbacks_t* GetCallbacks(void)
{
return &Callbacks;
}
Params_t* GetParams(void)
{
return &Params;
}
From the main file I call
typedef void (*OnJoin)(ActivationType_t Mode);
static OnJoinRequest JoinCB;
void Nemeus_Init_ReceiveCallback(OnJoin joinCB)
{
JoinCB = joinCB;
}
And then when I want to use my register callback I can't
...
if( 0 == memcmp(&addr, temp_uint8_array, sizeof(addr)) && NULL != JoinCB)
{
JoinCB(&(*(GetParams())->DefaultActivationType));
}
...
The error I have is : invalid type argument of '->' (have 'int').
I think it deals with the adress of GetParams that I want to dereference as adress are store in int.
It is quite complicated for me to understand whats going on but as I am a begginer I want to learn.
I thought that by writing this *(GetParams()) , I can acceed the structure and then by writing this &(*(GetParams())->DefaultActivationType) I can pass the adress of the structur field to the callback

C arrays of function pointers

I have three function arrays each pointing to a number of functions.
I can call any of those functions form the three tables.
Now I would like to dereference the three arrays into a single array of function pointers but I just can't get it working!
void afunc1(void);
void afunc2(void);
void afunc3(void);
void bfunc1(void);
void bfunc2(void);
void bfunc3(void);
void cfunc1(void);
void cfunc2(void);
void cfunc3(void);
void(*FuncTbla[])(void) = { afunc1, afunc2, afunc3 };
void(*FuncTblb[])(void) = { bfunc1, bfunc2, bfunc3 };
void(*FuncTblc[])(void) = { cfunc1, cfunc2, cfunc3 };
void (*AllFuncTbls[])(void) = { &FuncTbla, &FuncTblb, &FuncTblc };
int TblNo = 1, FuncNo = 1; // tblNo 1 = table b
bFunc2(); // calls bFunc2 directly
FuncTblb[FuncNo](); // Calls Function bFunc2 via function table b
// Call same function using table of function tables
AllFuncTbls[TblNo][FuncNo](); // Does not compile - expression must be a pointer to a complete object type!!!
Two things: First of all remember that arrays naturally decays to pointers to their first element; And secondly it will become so much easier if you use type-aliases for the function types.
Armed with that knowledge you could do it like e.g.
// Type-alias to simplify using function pointers
typedef void (*function_type)(void);
// The three tables
function_type FuncTbla[] = { &afunc1, &afunc2, &afunc3 };
function_type FuncTblb[] = { &bfunc1, &bfunc2, &bfunc3 };
function_type FuncTblc[] = { &cfunc1, &cfunc2, &cfunc3 };
// A table of pointers to the first elements of each array
function_type *AllFuncTbls[] = { FuncTbla, FuncTblb, FuncTblc };
To call a function using AllFuncTbls is as simple as
AllFuncTbls[TblNo][FuncNo]();
If you use typedefs it works:
void afunc1(void);
// ...
typedef void (*funcPtr)(void);
// void(*FuncTbla[])(void) = { afunc1, afunc2, afunc3 };
// ...
funcPtr FuncTbla[] = { afunc1, afunc2, afunc3 };
funcPtr FuncTblb[] = { bfunc1, bfunc2, bfunc3 };
funcPtr FuncTblc[] = { cfunc1, cfunc2, cfunc3 };
//void (*AllFuncTbls[])(void) = { &FuncTbla, &FuncTblb, &FuncTblc };
funcPtr* AllFuncTbls[] = { FuncTbla, FuncTblb, FuncTblc };
// Use an Array of pointers to function pointers here, not an array of function pointers!
// ...
// Call same function using table of function tables
AllFuncTbls[TblNo][FuncNo](); // Compiles now
I commented out the lines that had to be changed.
Using typealiases is better approach, but if you were courious how to do it without it:
void(**AllFuncTbls[])(void) = { FuncTbla, FuncTblb, FuncTblc};

object oriented approach in c program

I don't have much experience in Object oriented programming.I am trying to create an object in c which will have its own methods.
I have declared structure which have pointers to function. All instance of this variable are going to point same function. But currently I need to initialize every instance of variable as in main (Line 1 and Line 2). So is there any method that will initialize its default value when I declare it?
#include <stdio.h>
#include <stdlib.h>
typedef struct serialStr Serial;
struct serialStr
{
void(*init)(Serial*);
void(*open)();
void(*close)();
};
void open()
{
printf("Open Port Success\n");
return;
}
void close()
{
printf("Close port Success\n");
return;
}
void init(Serial* ptr)
{
ptr->open = open;
ptr->close = close;
}
int main()
{
Serial serial,serial_2;
serial.init = init;
serial.init(&serial); // Line1
serial_2.init = init;
serial_2.init(&serial_2); // Line2
serial.open();
//rest of code
serial.close();
serial_2.open();
serial_2.close();
return 0;
}
In C, the standard way would be to declare an initializer macro:
#define SERIAL_INITIALIZER { .init = init, .open = open, /* and others */ }
Serial serial = SERIAL_INITIALIZER;
In most cases in C there is simply no need for dynamic intialization of variables. You only need it for malloced objects.
C++ add some automatization by calling constructor/destructor. In pure C is no way to do so. You should do all steps manually: create and initialize object (call constructor-like function for structure), call functions by pointers from the structure instance, call destructor (it should destroy the instance and free related resources).
If is no polymorphism in your task then use simple way - without pointers to functions, but each function (method) should take pointer to the object.
Common case example:
struct MyStruct
{
// data
};
struct MyStruct* createMyStruct(/* maybe some input */)
{
// create, init and return the structure instance
}
void destoyMyStruct(struct MyStruct* obj)
{
// free resources and delete the instance
}
void doSomeAction(struct MyStruct* obj /* , some other data */)
{
// ...
}
int main()
{
struct MyStruct* object = createMyStruct();
doSomeAction(object);
destoyMyStruct(object);
return 0;
}
Edit 1: macro is only for very simple cases and error-prone way.
Typically, you would do this through "opaque type". Meaning that you declare an object of incomplete type in your header:
typedef struct Serial Serial;
And then in the C file, you place the actual struct definition. This will hide the contents of the struct to the caller (private encapsulation). From your constructor, you could then set up private member functions:
struct Serial
{
void(*init)(void);
void(*open)(void);
void(*close)(void);
};
// private member functions:
static void open (void);
...
// constructor:
Serial* SerialCreate (void)
{
Serial* s = malloc(sizeof (*s));
...
s->open = open;
return s;
}
This means that if you wish to inherit the class, you will only need to change the constructor.
Though of course, if you wish to implement true polymorphism, you don't want to change any code. You could solve this by passing the init function as parameter to the constructor.
header file:
typedef void init_func_t (void);
c file:
// constructor:
Serial* SerialCreate (init_func_t* init)
{
Serial* s = malloc(sizeof (*s));
...
init();
return s;
}
And then from the init function in the inherited class, set all private member functions.

passing argument from incompatible pointer type

static struct dll_wifi_state **dll_states;
enum dll_type {
DLL_UNSUPPORTED,
DLL_ETHERNET,
DLL_WIFI
};
struct dll_state {
enum dll_type type;
union {
struct dll_eth_state *ethernet;
struct dll_wifi_state *wifi;
} data;
};
static struct dll_state *dll_states = NULL;
struct dll_wifi_state {
int link;
// A pointer to the function that is called to pass data up to the next layer.
up_from_dll_fn_ty nl_callback;
bool is_ds;
};
This is the method whose pointer is being passed in the dll_wifi_state struct.
static void up_from_dll(int link, const char *data, size_t length)
{
//some code here
}
In other file, I am calling this method
void reboot_accesspoint()
{
// We require each node to have a different stream of random numbers.
CNET_srand(nodeinfo.time_of_day.sec + nodeinfo.nodenumber);
// Provide the required event handlers.
CHECK(CNET_set_handler(EV_PHYSICALREADY, physical_ready, 0));
// Prepare to talk via our wireless connection.
CHECK(CNET_set_wlan_model(my_WLAN_model));
// Setup our data link layer instances.
dll_states = calloc(nodeinfo.nlinks + 1, sizeof(struct dll_state));
for (int link = 0; link <= nodeinfo.nlinks; ++link) {
switch (linkinfo[link].linktype) {
case LT_LOOPBACK:
dll_states[link].type = DLL_UNSUPPORTED;
break;
case LT_WAN:
dll_states[link].type = DLL_UNSUPPORTED;
break;
case LT_LAN:
dll_states[link].type = DLL_ETHERNET;
dll_states[link].data.ethernet = dll_eth_new_state(link, up_from_dll);
break;
case LT_WLAN:
dll_states[link].type = DLL_WIFI;
dll_states[link].data.wifi = dll_wifi_new_state(link,
up_from_dll,
true /* is_ds */);
break;
}
}
// printf("reboot_accesspoint() complete.\n");
}
It works fine like this, but I want to add another argument i.e. up_from_dll((int link, const char *data, size_t length, int seq). And as soon as I add this argument, following error starts coming up
ap.c:153: warning: passing argument 2 of ‘dll_wifi_new_state’ from incompatible pointer type
Is there a way of adding another argument to that method without getting error ??? I am really bad with pointers :(
Any help would be much appreciated.
Line 153 :
dll_states[link].data.wifi = dll_wifi_new_state(link,
up_from_dll,
true /* is_ds */);
And method
struct dll_wifi_state *dll_wifi_new_state(int link,
up_from_dll_fn_ty callback,
bool is_ds)
{
// Ensure that the given link exists and is a WLAN link.
if (link > nodeinfo.nlinks || linkinfo[link].linktype != LT_WLAN)
return NULL;
// Allocate memory for the state.
struct dll_wifi_state *state = calloc(1, sizeof(struct dll_wifi_state));
// Check whether or not the allocation was successful.
if (state == NULL)
return NULL;
// Initialize the members of the structure.
state->link = link;
state->nl_callback = callback;
state->is_ds = is_ds;
return state;
}
I haven't changed anything else apart from adding the new parameter to up_from_dll.
The second parameter to dll_wifi_new_state is up_from_dll_fn_ty callback.
It's not in your code listing right now, but up_from_dll_fn_ty is a typedef saying that the up_from_dll_fn_ty is a function pointer with specific parameters (which don't include int seq)
When you updated up_from_dll with different parameters, it no longer matches the type specified by up_from_dll_fn_ty and expected as the second parameter for dll_wifi_new_state. You'll need to add the parameter to up_from_dll_fn_ty and you should be good.
If you post the definition of up_from_dll_fn_ty, it would make the question have all the information and allow me to help you more if you still need it.
You're looking for something like:
typedef void (*up_from_dll_fn_ty)(int link, const char *data, size_t length);
and change it to
typedef void (*up_from_dll_fn_ty)(int link, const char *data, size_t length, int seq);
Here's a link to a question that has good information about creating typedefs for function pointers:
Understanding typedefs for function pointers in C

Opaque C structs: various ways to declare them

I've seen both of the following two styles of declaring opaque types in C APIs. What are the various ways to declare opaque structs/pointers in C? Is there any clear advantage to using one style over the other?
Option 1
// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);
// foo.c
struct foo {
int x;
int y;
};
Option 2
// foo.h
typedef struct _foo foo;
void doStuff(foo *f);
// foo.c
struct _foo {
int x;
int y;
};
My vote is for the third option that mouviciel posted then deleted:
I have seen a third way:
// foo.h
struct foo;
void doStuff(struct foo *f);
// foo.c
struct foo {
int x;
int y;
};
If you really can't stand typing the struct keyword, typedef struct foo foo; (note: get rid of the useless and problematic underscore) is acceptable. But whatever you do, never use typedef to define names for pointer types. It hides the extremely important piece of information that variables of this type reference an object which could be modified whenever you pass them to functions, and it makes dealing with differently-qualified (for instance, const-qualified) versions of the pointer a major pain.
Option 1.5 ("Object-based" C Architecture):
I am accustomed to using Option 1, except where you name your reference with _h to signify it is a "handle" to a C-style "object" of this given C "class". Then, you ensure your function prototypes use const wherever the content of this object "handle" is an input only, and cannot be changed, and don't use const wherever the content can be changed. So, do this style:
// -------------
// my_module.h
// -------------
// An opaque pointer (handle) to a C-style "object" of "class" type
// "my_module" (struct my_module_s *, or my_module_h):
typedef struct my_module_s *my_module_h;
void doStuff1(my_module_h my_module);
void doStuff2(const my_module_h my_module);
// -------------
// my_module.c
// -------------
// Definition of the opaque struct "object" of C-style "class" "my_module".
struct my_module_s
{
int int1;
int int2;
float f1;
// etc. etc--add more "private" member variables as you see fit
};
Here's a full example using opaque pointers in C to create objects. The following architecture might be called "object-based C":
//==============================================================================================
// my_module.h
//==============================================================================================
// An opaque pointer (handle) to a C-style "object" of "class" type "my_module" (struct
// my_module_s *, or my_module_h):
typedef struct my_module_s *my_module_h;
// Create a new "object" of "class" "my_module": A function that takes a *pointer to* an
// "object" handle, `malloc`s memory for a new copy of the opaque `struct my_module_s`, then
// points the user's input handle (via its passed-in pointer) to this newly-created "object" of
// "class" "my_module".
void my_module_open(my_module_h * my_module_h_p);
// A function that takes this "object" (via its handle) as an input only and cannot modify it
void my_module_do_stuff1(const my_module_h my_module);
// A function that can modify the private content of this "object" (via its handle) (but still
// cannot modify the handle itself)
void my_module_do_stuff2(my_module_h my_module);
// Destroy the passed-in "object" of "class" type "my_module": A function that can close this
// object by stopping all operations, as required, and `free`ing its memory.
void my_module_close(my_module_h my_module);
//==============================================================================================
// my_module.c
//==============================================================================================
// Definition of the opaque struct "object" of C-style "class" "my_module".
// - NB: Since this is an opaque struct (declared in the header but not defined until the source
// file), it has the following 2 important properties:
// 1) It permits data hiding, wherein you end up with the equivalent of a C++ "class" with only
// *private* member variables.
// 2) Objects of this "class" can only be dynamically allocated. No static allocation is
// possible since any module including the header file does not know the contents of *nor the
// size of* (this is the critical part) this "class" (ie: C struct).
struct my_module_s
{
int my_private_int1;
int my_private_int2;
float my_private_float;
// etc. etc--add more "private" member variables as you see fit
};
void my_module_open(my_module_h * my_module_h_p)
{
// Ensure the passed-in pointer is not NULL (since it is a core dump/segmentation fault to
// try to dereference a NULL pointer)
if (!my_module_h_p)
{
// Print some error or store some error code here, and return it at the end of the
// function instead of returning void.
goto done;
}
// Now allocate the actual memory for a new my_module C object from the heap, thereby
// dynamically creating this C-style "object".
my_module_h my_module; // Create a local object handle (pointer to a struct)
// Dynamically allocate memory for the full contents of the struct "object"
my_module = malloc(sizeof(*my_module));
if (!my_module)
{
// Malloc failed due to out-of-memory. Print some error or store some error code here,
// and return it at the end of the function instead of returning void.
goto done;
}
// Initialize all memory to zero (OR just use `calloc()` instead of `malloc()` above!)
memset(my_module, 0, sizeof(*my_module));
// Now pass out this object to the user, and exit.
*my_module_h_p = my_module;
done:
}
void my_module_do_stuff1(const my_module_h my_module)
{
// Ensure my_module is not a NULL pointer.
if (!my_module)
{
goto done;
}
// Do stuff where you use my_module private "member" variables.
// Ex: use `my_module->my_private_int1` here, or `my_module->my_private_float`, etc.
done:
}
void my_module_do_stuff2(my_module_h my_module)
{
// Ensure my_module is not a NULL pointer.
if (!my_module)
{
goto done;
}
// Do stuff where you use AND UPDATE my_module private "member" variables.
// Ex:
my_module->my_private_int1 = 7;
my_module->my_private_float = 3.14159;
// Etc.
done:
}
void my_module_close(my_module_h my_module)
{
// Ensure my_module is not a NULL pointer.
if (!my_module)
{
goto done;
}
free(my_module);
done:
}
Simplified example usage:
#include "my_module.h"
#include <stdbool.h>
#include <stdio.h>
int main()
{
printf("Hello World\n");
bool exit_now = false;
// setup/initialization
my_module_h my_module = NULL;
// For safety-critical and real-time embedded systems, it is **critical** that you ONLY call
// the `_open()` functions during **initialization**, but NOT during normal run-time,
// so that once the system is initialized and up-and-running, you can safely know that
// no more dynamic-memory allocation, which is non-deterministic and can lead to crashes,
// will occur.
my_module_open(&my_module);
// Ensure initialization was successful and `my_module` is no longer NULL.
if (!my_module)
{
// await connection of debugger, or automatic system power reset by watchdog
log_errors_and_enter_infinite_loop();
}
// run the program in this infinite main loop
while (exit_now == false)
{
my_module_do_stuff1(my_module);
my_module_do_stuff2(my_module);
}
// program clean-up; will only be reached in this case in the event of a major system
// problem, which triggers the infinite main loop above to `break` or exit via the
// `exit_now` variable
my_module_close(my_module);
// for microcontrollers or other low-level embedded systems, we can never return,
// so enter infinite loop instead
while (true) {}; // await reset by watchdog
return 0;
}
The only improvements beyond this would be to:
Implement full error handling and return the error instead of void. Ex:
/// #brief my_module error codes
typedef enum my_module_error_e
{
/// No error
MY_MODULE_ERROR_OK = 0,
/// Invalid Arguments (ex: NULL pointer passed in where a valid pointer is required)
MY_MODULE_ERROR_INVARG,
/// Out of memory
MY_MODULE_ERROR_NOMEM,
/// etc. etc.
MY_MODULE_ERROR_PROBLEM1,
} my_module_error_t;
Now, instead of returning a void type in all of the functions above and below, return a my_module_error_t error type instead!
Add a configuration struct called my_module_config_t to the .h file, and pass it in to the open function to update internal variables when you create a new object. This helps encapsulate all configuration variables in a single struct for cleanliness when calling _open().
Example:
//--------------------
// my_module.h
//--------------------
// my_module configuration struct
typedef struct my_module_config_s
{
int my_config_param_int;
float my_config_param_float;
} my_module_config_t;
my_module_error_t my_module_open(my_module_h * my_module_h_p,
const my_module_config_t *config);
//--------------------
// my_module.c
//--------------------
my_module_error_t my_module_open(my_module_h * my_module_h_p,
const my_module_config_t *config)
{
my_module_error_t err = MY_MODULE_ERROR_OK;
// Ensure the passed-in pointer is not NULL (since it is a core dump/segmentation fault
// to try to dereference a NULL pointer)
if (!my_module_h_p)
{
// Print some error or store some error code here, and return it at the end of the
// function instead of returning void. Ex:
err = MY_MODULE_ERROR_INVARG;
goto done;
}
// Now allocate the actual memory for a new my_module C object from the heap, thereby
// dynamically creating this C-style "object".
my_module_h my_module; // Create a local object handle (pointer to a struct)
// Dynamically allocate memory for the full contents of the struct "object"
my_module = malloc(sizeof(*my_module));
if (!my_module)
{
// Malloc failed due to out-of-memory. Print some error or store some error code
// here, and return it at the end of the function instead of returning void. Ex:
err = MY_MODULE_ERROR_NOMEM;
goto done;
}
// Initialize all memory to zero (OR just use `calloc()` instead of `malloc()` above!)
memset(my_module, 0, sizeof(*my_module));
// Now initialize the object with values per the config struct passed in. Set these
// private variables inside `my_module` to whatever they need to be. You get the idea...
my_module->my_private_int1 = config->my_config_param_int;
my_module->my_private_int2 = config->my_config_param_int*3/2;
my_module->my_private_float = config->my_config_param_float;
// etc etc
// Now pass out this object handle to the user, and exit.
*my_module_h_p = my_module;
done:
return err;
}
And usage:
my_module_error_t err = MY_MODULE_ERROR_OK;
my_module_h my_module = NULL;
my_module_config_t my_module_config =
{
.my_config_param_int = 7,
.my_config_param_float = 13.1278,
};
err = my_module_open(&my_module, &my_module_config);
if (err != MY_MODULE_ERROR_OK)
{
switch (err)
{
case MY_MODULE_ERROR_INVARG:
printf("MY_MODULE_ERROR_INVARG\n");
break;
case MY_MODULE_ERROR_NOMEM:
printf("MY_MODULE_ERROR_NOMEM\n");
break;
case MY_MODULE_ERROR_PROBLEM1:
printf("MY_MODULE_ERROR_PROBLEM1\n");
break;
case MY_MODULE_ERROR_OK:
// not reachable, but included so that when you compile with
// `-Wall -Wextra -Werror`, the compiler will fail to build if you forget to handle
// any of the error codes in this switch statement.
break;
}
// Do whatever else you need to in the event of an error, here. Ex:
// await connection of debugger, or automatic system power reset by watchdog
while (true) {};
}
// ...continue other module initialization, and enter main loop
See also:
[another answer of mine which references my answer above] Architectural considerations and approaches to opaque structs and data hiding in C
Additional reading on object-based C architecture:
Providing helper functions when rolling out own structures
Additional reading and justification for valid usage of goto in error handling for professional code:
An argument in favor of the use of goto in C for error handling: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/Research_General/goto_for_error_handling_in_C/readme.md
*****EXCELLENT ARTICLE showing the virtues of using goto in error handling in C: "Using goto for error handling in C" - https://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c
Valid use of goto for error management in C?
Error handling in C code
Search terms to make more googlable: opaque pointer in C, opaque struct in C, typedef enum in C, error handling in C, c architecture, object-based c architecture, dynamic memory allocation at initialization architecture in c
bar(const fooRef) declares an immutable address as argument. bar(const foo *) declares an address of an immutable foo as argument.
For this reason, I tend to prefer option 2. I.e., the presented interface type is one where cv-ness can be specified at each level of indirection. Of course one can sidestep the option 1 library writer and just use foo, opening yourself to all sorts of horror when the library writer changes the implementation. (I.e., the option 1 library writer only perceives that fooRef is part of the invariant interface and that foo can come, go, be altered, whatever. The option 2 library writer perceives that foo is part of the invariant interface.)
I'm more surprised that no one's suggested combined typedef/struct constructions.
typedef struct { ... } foo;
Option 3: Give people choice
/* foo.h */
typedef struct PersonInstance PersonInstance;
typedef struct PersonInstance * PersonHandle;
typedef const struct PersonInstance * ConstPersonHandle;
void saveStuff (PersonHandle person);
int readStuff (ConstPersonHandle person);
...
/* foo.c */
struct PersonInstance {
int a;
int b;
...
};
...

Resources