I have a code that does OOP like Java.
I have separated the interface and the implementation in separate files names demo.h and demo.c.
demo.h
#ifndef DEMO_H
#define DEMO_H
typedef struct {
/*
This is the variable that will be set by setter method
and its value will be extracted by getter method.
This variable must not be directly accessible by the programmer.
*/
int num;
void (* setNum)(int); // This function will set the value of variable "num".
int (* getNum)(); // This function will return the value of variable "num".
} *Demo; // As objects in java are always called by reference.
Demo newDemo(); // This function will create an instance of class(struct here) Demo and return.
/* This is equivalent to:
Demo obj = new Demo();
int java.
I want my users to create instance of this class(struct here) like this:
Demo obj = newDemo();
here in this code.
*/
#endif
And the implementation:
demo.c
#include <stdlib.h>
#include "demo.h"
Demo demo; /* I have created a global variable so that it is accessible
in setNum and getNum functions. */
void setNum(int num) {
demo->num = num; // This is where the global demo is accessed.
}
int getNum(Demo obj) {
return demo->num; // This is where the global demo is accessed.
}
Demo newDemo() {
Demo obj; // This will be the returned object.
obj = (Demo)malloc(sizeof(*obj)); /* Allocating separate memory to
obj each time this function is called. */
/* Setting the function pointer. */
obj->setNum = setNum;
obj->getNum = getNum;
/* As obj is at different memory location every time this function is called,
I am assigning that new location the the global demo variable. So that each variable
of the Demo class(struct here) must have a different object at different memory
location. */
demo = obj;
return obj; // Finally returning the object.
}
This is how I have implemented the main function:
main.c
#include "demo.h"
#include <stdio.h>
int main() {
void displayData(Demo);
Demo obj1 = newDemo();
Demo obj2 = newDemo();
Demo obj3 = newDemo();
obj1->setNum(5);
obj2->setNum(4);
obj3->setNum(12);
displayData(obj1);
displayData(obj2);
displayData(obj3);
return 0;
}
void displayData(Demo obj) {
int num = obj->getNum();
fprintf(stdout, "%d\n", num);
}
On compilation and execution on my mac book pro:
> gcc -c demo.c
> gcc main.c demo.o -o Demo
> ./Demo
The output is:
12
12
12
But the desired output is:
5
4
12
What am I doing wrong?
Please help.
I don't want my users to pass the struct pointer as an argument as:
Demo obj = newDemo();
obj->setName(obj, "Aditya R.Singh"); /* Creating the program this way was successful as my
header file had the declaration as:
typedef struct demo {
int num;
void (* setNum)(struct demo, int); // This is what I don't desire.
void (* getNum)(struct demo); // This is what I don't desire.
} *Demo;
I want to keep it like the way it is in my current
demo.h*/
/* I don't want to pass obj as an argument. All I want to do this is this way. */
obj->setName("Aditya R.Singh");
Is there any way possible to do this and get the desired output?
Please help, thanks!
I have absolutely no idea of c++, but in your code, I think, demo = obj; is the problem. demo is global, right? It will get overwritten with evety call to newDemo().
Side effect : Memory leak.
Related
I'm writing "threaded interpreter" using computed goto. How do I initialize address lookup table to be visible from different functions without additional runtime cost?
Label address is only visible at same function and static lookup table is initialized by compiler in data section without runtime cost at each call. But it's visible only in same function and I want to have another function to have access to it, for example to cache addresses and save lookups in main interpreter code. I can take pointer to this table and store it somewhere, but it will happen every time function is called, and it will get called frequently. Yes, it's just only one mov, but is there another way?
#include <stdio.h>
static void** table_ptr;
// how do i declare static variable and init it later once?
// Tried this. Generates runtime assigns at each call. Not unexpected
// static void** jumps_addr;
int main()
{
// labels are visible only inside the function
// generates runtime assigns at each call
// jumps_addr = (void* [10]){
// this initializes it in static data section, but name is only visible inside this function
static void* jumps_addr[10] = {
[1] = &&operation_print,
};
// want another way instead of this
table_ptr = jumps_addr;
// not optimize this
volatile int opcode = 1;
goto *jumps_addr[opcode];
return 0;
operation_print:;
printf("hello\n");
return 0;
}
void do_some_preprocessing_work(void){
// want access to jumps_addr table here
// without having to store it somewhere
// [do something with table_ptr]
// this is to prevent optimization to explore what compiler does on godbolt.org
// because it will optimize away table_ptr entirely if not used
volatile i = 1;
i += table_ptr[i];
//actual code here will store labbel addrs into opcode struct to save table lookup at runtime
}
The solution might sound unorthodox, but how about not to use any functions, but only goto.
Like so:
#include <stdio.h>
int main()
{
volatile int opcode;
static void* jumps_addr[10] = {
[0] = &&do_some_preprocessing_work,
[1] = &&operation_print
};
opcode = 0;
goto *jumps_addr[opcode];
return 1;
operation_print:
printf("hello\n");
return 0;
do_some_preprocessing_work:
printf("jumps_addr[%i]\n", ++opcode);
goto *jumps_addr[opcode];
return 1;
}
Hi All here is my specific case:
service.h:
typedef struct {
uint8_t (*function1)(void);
uint8_t (*function2)(void);
} const service_struct_t;
extern service_struct_t service_api ;
service.c:
#include "service.h"
static uint8_t foo(void){
return 13+6;
}
static uint8_t bar(void){
return 7*6;
}
service_struct_t service_api = {
.function1 = foo,
.function2 = bar,
};
I need to stub (to mock, to replace) these functions but I have no right to change that original code. I'm using gcc to compile the unit tests. I've failed to:
use the --wrap option of gcc straight on foo and bar since they are static to source.c :
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_foo(void);
uint8_t __wrap_foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}
/* same for bar */
use the --wrap option of gcc onto the service_api object symbol because it's not a function
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_service_api ;
uint8_t __wrap_service_api = {
.function1 = foo,
.function2 = bar,
}
static uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_service_api.function1();
}
}
/* same for bar */
simply reassign the service_api member functions since the structure is constant and already assigned.
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
service_struct_t backup_service_api = {
.function1 = service_api.function1;
.function2 = service_api.function2;
}
service_struct_t stub_service_api = {
.function1 = foo;
.function2 = bar;
}
uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}/* same for bar */
void service_poke_stub(bool_t enable_stubs){
if(enable_stubs){
service_api.function1 = stub_service_api.function1
service_api.function2 = stub_service_api.function2
}else{
service_api.function1 = backup_service_api.function1
service_api.function2 = backup_service_api.function2
}
}
thanks already for your help
You can't mock the functions in the structure, as you already found out.
So it depends on what you like to test:
If you want to test whether the structure contains the correct functions, the module service.c is your module-under-test and should be used as is. You need to check the correctness by watching what is done by the functions.
If you want to test that the structure is used correctly, you will mock the whole module. Now you are free to put in it whatever you want.
If your source code does not allow this, the design is bad for testing. This is often the case when the architecture is not done with testability in mind.
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.
My program contains the following files: data_handler.c, app.c and callback_struct.h.
data_handler.c retrieves data from functions in app.c, by making callbacks to app.c.
The program should allow the user to define a set of functions with arbitrary names in app.c. The user does this by defining his functions, and associating them with a set of initiated function pointers (ptr_func1, ptr_func2 etc.), found in callback_struct.h.
With this approach I want to eliminate the need of making explicit calls from data_handler.c to the user functions in app.c (so that the code in data_handler.c do not have to be modified if the user changes his function names for example), neither do I want to have to include (#) app.c into data_handler.c.
Clearly there is something I'm not getting here. I would be grateful if someone could help me understand what I'm doing wrong, and perhaps give me some indications on whether or not I'm on the right track with my suggested implementation
See my implementation below:
callback_struct.h:
struct callback_struct{
int (*ptr_func1)(void);
int (*ptr_func2)(void);
// etc...
};
extern struct callback_struct user_functions; // should be defined in app.c
app.c
#include "callback_struct.h"
int user_function_func1(void);
int user_function_func2(void);
struct callback_struct user_functions={
.ptr_func1 = user_function_func1,
.ptr_func2 = user_function_func2,
};
int user_function_func1(void){
int data = 1; // for example...
return data;
}
int user_function_func2(void){
int data = 2; // for example...
return data;
}
// etc.....
data_handler.c
#include "callback_struct.h"
/*this function makes callbacks to app.c to retrieve data*/
void get_data(int (*ptr)(void)){
int retrieved_data=ptr();
}
void main(void){
get_data(user_functions.ptr_func1);
get_data(user_functions.ptr_func2);
// etc....
}
It's only a syntax error. Just replace
extern struct user_functions={
by
struct callback_struct user_functions={
in your app.c and it will work.
When you declare a global variable 'extern', you are telling the compiler that this variable is instantiated (and possibly initialized) somewhere else in the code.
Therefore, you should not declare it 'extern' and initialize it in the same line, which is exactly what you did in file app.c.
I have a project, and a case where I have a few often-changed preprocessor #defines that control how it works--ex:
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
#ifdef FEATURE_X
feature_x(content);
#endif
}
This works fine, although it does have to be recompiled each time, so it's in the "stuff that has to be recompiled each time" file. I would like to push it into a [static] library instead. I'm ok with changing how it's called (already have a function pointer for picking myFunction), so I'd like that to turn into
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
}
void myfunction_featureX(int num, mystruct* content) {
doSomethingTo(content);
//...
feature_x(content);
}
I need to do this in a couple places, so using a separate library (one with and one without -D FEATURE_X) for each isn't an acceptable option. I could do it with copy/paste, but that results in code reuse that carries a risk of fixing a bug in one copy but not the other.
Have the featureX versions of functions call the mainline functions. In your example myfunction_featureX would call myfunction and then do its own thing.
Surely, this is the point at which you change the activation of Feature X from a compile time issue into a run-time issue:
void myfunction(int num, mystruct* content)
{
doSomethingTo(content);
//...
if (FeatureX_Enabled())
feature_x(content);
}
The FeatureX_Enabled() test might be a full function, or it might be simply test an appropriately scoped variable that is defined outside the function — a static variable in the file, or an external variable. This avoids having to futz with the function pointers; it's the same function called as now. Changing a table of function pointers is equivalent to changing a single variable — it involves changing the value of something stored outside the function to change the behaviour of the function.
Would it help if you put myfeature_x in a function table instead?
#include <stdio.h>
#include <string.h>
typedef struct {
int x,y;
} mystruct;
typedef void (*fn_ptr)(mystruct* content);
fn_ptr vtable[10];
#define FEATURE_X_INDEX 0
void feature_x(mystruct *content)
{
printf("y: %d\n", content->y);
}
void myfunction(int num, mystruct* content) {
printf("x: %d\n", content->x);
//...
if (vtable[FEATURE_X_INDEX]) {
vtable[FEATURE_X_INDEX](content);
}
}
int main(void)
{
bzero(vtable, sizeof(vtable));
mystruct s;
s.x = 1;
s.y = 2;
myfunction(0, &s);
if (1) {
//Of course you'd use a more sensible condition.
vtable[FEATURE_X_INDEX] = feature_x;
}
myfunction(0, &s);
return 0;
}
Output:
x: 1
x: 1
y: 2
Then all you need to do is populate the virtual function table with NULLs if that feature is not to be used, and with function pointers if it is to be used. This you can do from wherever you want - your static library for example.. or you can compile feature_x into a dynamic library, load it at runtime and if the loading succeeded populate the function table, and clear the table when the dynamically linked library is unloaded.
I think the only benefit this really gives you over Jonathan Leffler's method is that the code for feature_x doesn't actually need to be linked into the same binary as your other code. If all you need is a runtime switch to turn the feature on or off, a simple if statement should do the trick, as Jonathan Leffler suggested. (Incidentally, there's an if here, too - it checks the function table's content :) )