C embedded change values of struct from another file - c

Hello I am working on a small roboter project at uni and I have run into following issue.
I have a typedef called RoboterData inside of a header file because I want to make use of it across multiple files. Inside of the main file I have a RoboterData data variable which holds important data.
My goal is to have access from other files to this data having the ability to get and set it from another file. I want to avoid the use of a global variable.
Here are the relevant code fragments of my approach:
main.h
typedef struct {
DriveMode mode;
short sensor_left;
short sensor_mid;
short sensor_right;
int left_eng_speed;
int right_eng_speed;
} RoboterData;
main.c
# include "motors.h"
// The Data I want to get and set from other files.
RoboterData data;
// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
motors.h
void drive_straight(RoboterData *data);
motors.c
# include "main.h"
enum {
ENG_STILL = 0,
ENG_SLOW = 50,
ENG_MID = 155,
ENG_FAST = 200
}
void drive_straight(RoboterData *data) {
data ->left_eng_speed = ENG_FAST;
data ->right_eng_speed = ENG_FAST;
set_duty_cycle(LEFT_ENG, ENG_FAST);
set_duty_cycle(RIGHT_ENG, ENG_FAST);
}
When I later try to print out the values left_eng_speed and right_eng_speed via serial port it stays at 0. I know C is call by value but since I am passing a ptr to my struct the value I am passing is the adress of the struct and when I dereference it via '->' I should be able to access its original data from my understanding and not a copy because the only thing I copied was the address.
If someone could explain to me why this is not working and provide a viable alternative, I would be very greatfull.

// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
This is a function declaration. It doesn't do anything. You want
drive_straight(&data);
to actually call the function.

Related

Update global C struct using only one function without passing whole data structure

I am developing a database access layer to store data of software subsystems. The database interface has two functions, database_get() and database_set(). They take two arguments, first is a ID that identifies the software component and the second argument is a typedef struct that holds the new settings for this software component. Then i have:
#define COMPONENT1_ID 7
typedef struct
{
int member1;
char member2;
char member3;
} COMPONENT1_STRUCT_T ;
I can store and retrieve persistent data calling the database_set(COMPONENT1_ID, (void *) &new_struct) and database_get(COMPONENT1_ID, (void *) &new_struct) functions. It works the same for storing data from any other software subsystem using this database.
Now i am developing APIs to manage this software subsystems. This APIs are used by the user interfaces. The API of a software subsystem is taking care of performing all the logic behind the component and also calling the database to make its data persistent. I have developed a function for the API which carries out the operation and finally call a function like this:
int save_new_member1_db(int member1);
{
COMPONENT1_STRUCT_T new_setting;
database_get(COMPONENT1_ID, (void *)&new_setting);
new_setting.member1 = member1;
database_set(COMPONENT1_ID, (void *)&new_setting);
}
I wonder if i can avoid creating a new function to update each member data in the database.
Also I dont want a big function taking the whole struct or all members of the struct if it means the subsystem API gets reduced to one function. The subsystem can be a LED display and its API could be different methods doing one thing as update_led_display_color(const LED_DISPLAY_COLOR new color), update_led_display_font(const LED_DISPLAY_FONT cur_font), get_led_display_font(LED_DISPLAY_FONT *cur_font) ...
You are going to need some kind of mapping between a symbolic constant representing a member and information you need to set that member. You could use something like your "COMPONENT1_ID" for each member and have an array of size+offset information for each member like so:
#include <stdio.h>
#include <stddef.h>
#include <string.h>
// in header file (or wherever so that it is visible to
// the definition of "Test_save_member" and not a part of
// the subsystem API)
#define TEST_ID 7
// in a c file (in your database implementation, I assume)
typedef struct
{
int mem1;
char mem2;
char mem3;
} Test;
// for sure in header file exposed in your subsystem API
typedef enum
{
MEM1,
MEM2,
MEM3,
NUM_MEMBERS
} TestMember;
// in c file (in your database implementation, I assume again)
typedef struct
{
size_t offset;
size_t size;
} MemberInfo;
static MemberInfo member_info[NUM_MEMBERS] =
{
{ offsetof(Test, mem1), sizeof(int) },
{ offsetof(Test, mem2), sizeof(char) },
{ offsetof(Test, mem3), sizeof(char) }
};
// also a part of your subsystem API
int Test_save_member(TestMember member, void* value)
{
if (!value || member < 0 || member >= NUM_MEMBERS))
return 0;
Test new_setting;
database_get(TEST_ID, (void *)&new_setting);
MemberInfo info = member_info[member];
memcpy((char*)(&new_setting) + info.offset, value, info.size);
database_set(TEST_ID, (void *)&new_setting);
return 1;
}
// subsystem API usage
int main(void)
{
int new_mem1 = 5;
Test_save_member(MEM1, &new_mem1);
return 0;
}
Depending upon whether you want to edit your database functions, the amount of coupling you want to deal with, etc, this could change drastically; I don't think, however, that you can get away without some type of mapping given the constraints you mentioned.
This particular implementation would disallow passing literals, but that shouldn't be too big of an issue (to deal with or work around).

Implementing callbacks between files in C

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.

C append to an array in header file

I have multiple header files, each of them must append a number to an array to register it's functions.
Currently I have a function with a unique name in each header file, and in the program file I need to call all those functions in one combining function.
int register1() { return 100; }; //in header1.h
int register2() { return 200; }; //in header2.h
int register3() { return 300; }; //in header3.h
int register4() { return 400; }; //in header4.h
int registered[] = {register1(),register2(),register3(),register4()}; //main.c
But this is quite inconvenient because I need to modify in two places when I add or remove header files. Better would be to modify the header file only. I was thinking about a preprocessor define, so in each header I can just use something like:
#define Registered Registered,100 // header1.h
#define Registered Registered,200 // header2.h
int registered[] = {Registered}; // main.c
But this of course will not compile, because new define redefines the old one. So is there a way to append a define? Or other way to append a number to an array without modifying two files?
This is C, not C++, otherwise I would use a class instance with constructor that would just write to an array. Somethink like that:
struct __header1{ __header1() {
global_array[global_array_ptr++] = 100;
} } __header1_inst;
and then convert it to a nice macro:
#define register(hdr, func) struct __header##hdr{ __header##hdr() { \
global_array[global_array_ptr++] = func; \
} } __header##hdr##_inst;
register(1, 100) // header1.h
register(2, 200) // header2.h
IMHO, this is a hack and I would advise against it. Even if you could do that in C, consider situation where one such header file is included by several modules. There will be an identical entry in the global array for every such module. Next, even though you can do it in C++, the order of global object initialization is undefined there, so initialization of another global object relying on contents of the global array will be unreliable.
Additionally, this is a really complicated way to do a simple thing, and obscures the meaning considerably. Apart from the array-filling code itself being complex, tracking includes will become burdensome when dependencies get beyond trivial. So, just fill that global array in a specific place explicitly.

How avoid using global variable when using nftw

I want to use nftw to traverse a directory structure in C.
However, given what I want to do, I don't see a way around using a global variable.
The textbook examples of using (n)ftw all involve doing something like printing out a filename. I want, instead, to take the pathname and file checksum and place those in a data structure. But I don't see a good way to do that, given the limits on what can be passed to nftw.
The solution I'm using involves a global variable. The function called by nftw can then access that variable and add the required data.
Is there any reasonable way to do this without using a global variable?
Here's the exchange in previous post on stackoverflow in which someone suggested I post this as a follow-up.
Using ftw can be really, really bad. Internally it will save the the function pointer that you use, if another thread then does something else it will overwrite the function pointer.
Horror scenario:
thread 1: count billions of files
thread 2: delete some files
thread 1: ---oops, it is now deleting billions of
files instead of counting them.
In short. You are better off using fts_open.
If you still want to use nftw then my suggestion is to put the "global" type in a namespace and mark it as "thread_local". You should be able to adjust this to your needs.
/* in some cpp file */
namespace {
thread_local size_t gTotalBytes{0}; // thread local makes this thread safe
int GetSize(const char* path, const struct stat* statPtr, int currentFlag, struct FTW* internalFtwUsage) {
gTotalBytes+= statPtr->st_size;
return 0; //ntfw continues
}
} // namespace
size_t RecursiveFolderDiskUsed(const std::string& startPath) {
const int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;
const int maxFileDescriptorsToUse = 1024; // or whatever
const int result = nftw(startPath.c_str(), GetSize, maxFileDescriptorsToUse , flags);
// log or something if result== -1
return gTotalBytes;
}
No. nftw doesn't offer any user parameter that could be passed to the function, so you have to use global (or static) variables in C.
GCC offers an extension "nested function" which should capture the variables of their enclosing scopes, so they could be used like this:
void f()
{
int i = 0;
int fn(const char *,
const struct stat *, int, struct FTW *) {
i++;
return 0;
};
nftw("path", fn, 10, 0);
}
The data is best given static linkage (i.e. file-scope) in a separate module that includes only functions required to access the data, including the function passed to nftw(). That way the data is not visible globally and all access is controlled. It may be that the function that calls ntfw() is also part of this module, enabling the function passed to nftw() to also be static, and thus invisible externally.
In other words, you should do what you are probably doing already, but use separate compilation and static linkage judiciously to make the data only visible via access functions. Data with static linkage is accessible by any function within the same translation unit, and you avoid the problems associated with global variables by only including functions in that translation unit that are creators, maintainers or accessors of that data.
The general pattern is:
datamodule.h
#if defined DATAMODULE_INCLUDE
<type> create_data( <args>) ;
<type> get_data( <args> ) ;
#endif
datamodule.c
#include "datamodule.h"
static <type> my_data ;
static int nftwfunc(const char *filename, const struct stat *statptr, int fileflags, struct FTW *pfwt)
{
// update/add to my_data
...
}
<type> create_data( const char* path, <other args>)
{
...
ret = nftw( path, nftwfunc, fd_limit, flags);
...
}
<type> get_data( <args> )
{
// Get requested data from my_data and return it to caller
}

How do I write a dispatcher, if my compiler's support for pointers-to-functions is broken?

I am working on an embedded application where the device is controlled through a command interface. I mocked the command dispatcher in VC and had it working to my satisfaction; but when I then moved the code over to the embedded environment, I found out that the compiler has a broken implementation of pointer-to-func's.
Here's how I originally implemented the code (in VC):
/* Relevant parts of header file */
typedef struct command {
const char *code;
void *set_dispatcher;
void *get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, &set_##dispatcher, &get_##dispatcher, (const char*)description}
/* Dispatcher data structure in the C file */
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)"),
COMMAND_ENTRY("IP", Ip, "IP Address (192.168.1.205)"),
COMMAND_ENTRY("SM", Subnet, "Subunet Mask (255.255.255.0)"),
COMMAND_ENTRY("DR", DefaultRoute, "Default router (192.168.1.1)"),
COMMAND_ENTRY("UN", Username, "Web username"),
COMMAND_ENTRY("PW", Password, "Web password"),
...
}
/* After matching the received command string to the command "label", the command is dispatched */
if (pc->isGetter)
return ((get_fn_t)(commands[i].get_dispatcher))(pc);
else
return ((set_fn_t)(commands[i].set_dispatcher))(pc);
}
Without the use of function pointers, it seems like my only hope is to use switch()/case statements to call functions. But I'd like to avoid having to manually maintain a large switch() statement.
What I was thinking of doing is moving all the COMMAND_ENTRY lines into a separate include file. Then wraps that include file with varying #define and #undefines. Something like:
/* Create enum's labels */
#define COMMAND_ENTRY(label,dispatcher,description) SET_##dispatcher, GET_##dispatcher
typedef enum command_labels = {
#include "entries.cinc"
DUMMY_ENUM_ENTRY} command_labels_t;
#undefine COMMAND_ENTRY
/* Create command mapping table */
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, SET_##dispatcher, GET_##dispatcher, (const char*)description}
const command_t commands[] = {
#include "entries.cinc"
NULL /* dummy */ };
#undefine COMMAND_ENTRY
/*...*/
int command_dispatcher(command_labels_t dispatcher_id) {
/* Create dispatcher switch statement */
#define COMMAND_ENTRY(label,dispatcher,description) case SET_##dispatcher: return set_##dispatcher(pc); case GET_##dispatcher: return get_##dispatcher(pc);
switch(dispatcher_id) {
#include "entries.cinc"
default:
return NOT_FOUND;
}
#undefine COMMAND_ENTRY
}
Does anyone see a better way to handle this situation? Sadly, 'get another compiler' is not a viable option. :(
--- Edit to add:
Just to clarify, the particular embedded environment is broken in that the compiler is supposed to create a "function-pointer table" which is then used by the compiler to resolve calls to functions through a pointer. Unfortunately, the compiler is broken and doesn't generate a correct function-table.
So I don't have an easy way to extract the func address to invoke it.
--- Edit #2:
Ah, yes, the use of void *(set|get)_dispatcher was my attempt to see if the problem was with the typedefine of the func pointers. Originally, I had
typedef int (*set_fn_t)(cmdContext_t *pCmdCtx);
typedef int (*get_fn_t)(cmdContext_t *pCmdCtx);
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
You should try changing your struct command so the function pointers have the actual type:
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
Unfortunately, function pointers are not guaranteed to be able to convert to/from void pointers (that applies only to pointers to objects).
What's the embedded environment?
Given the information posted in the updates to the question, I see that it's really a bugged compiler.
I think that your proposed solution seems pretty reasonable - it's probably similar to what I would have come up with.
A function pointer isn't actually required to fit in a void*. You could check to make sure that the value you're calling is actually the address of the function. If not, use a function pointer type in the struct: either get_fn_t, or IIRC void(*)(void) is guaranteed to be compatible with any function pointer type.
Edit: OK, assuming that calling by value can't be made to work, I can't think of a neater way to do what you need than auto-generating the switch statement. You could maybe use an off-the-shelf ASP-style preprocessor mode for ruby/python/perl/php/whatever prior to the C preprocessor. Something like this:
switch(dispatcher_id) {
<% for c in commands %>
case SET_<% c.dispatcher %>: return set_<% c.dispatcher %>(pc);
case GET_<% c.dispatcher %>: return get_<% c.dispatcher %>(pc);
<% end %>
default:
return NOT_FOUND;
}
might be a bit more readable than the macro/include trick, but introducing a new tool and setting up the makefiles is probably not worth it for such a small amount of code. And the line numbers in the debug info won't relate to the file you think of as the source file unless you do extra work in your preprocessor to specify them.
Can you get the vendor to fix the compiler?
To what extent is the pointer-to-function broken?
If the compiler allows you to get the address of a function (I'm from C++, but &getenv is what I mean), you could wrap the calling convention stuff into assembler.
As said, I'm a C++ssie, but something in the way of
; function call
push [arg1]
push [arg2]
call [command+8] ; at the 4th location, the setter is stored
ret
If even that is broken, you could define an array of extern void* pointers which you define, again, in assembly.
try this syntax:
return (*((get_fn_t)commands[i].get_dispatcher))(pc);
It's been awhile since I've done C & function pointers, but I believe the original C syntax required the * when dereferencing function pointers but most compilers would let you get away without it.
Do you have access to the link map?
If so, maybe you can hack your way around the wonky function-pointer table:
unsigned long addr_get_dhcp = 0x1111111;
unsigned long addr_set_dhcp = 0x2222222; //make these unique numbers.
/* Relevant parts of header file */
typedef struct command {
const char *code;
unsigned long set_dispatcher;
unsigned long get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label,
addr_set_##dispatcher, addr_get_##dispatcher, (const char*)description}
Now compile, grab the relevant addresses from the link map, replace the constants, and recompile. Nothing should move, so the map ought to stay the same. (Making the original constants unique should prevent the compiler from collapsing identical values into one storage location. You may need a long long, depending on the architecture)
If the concept works, you could probably add a post-link step running a script to do the replacement automagically. Of course, this is just a theory, it may fail miserably.
Maybe, you need to look into the structure again:
typedef struct command {
const char *code;
void *set_dispatcher; //IMO, it does not look like a function pointer...
void *get_dispatcher; //more like a pointer to void
const char *_description;
} command_t;
Let say your dispatchers have the following similar function definition:
//a function pointer type definition
typedef int (*genericDispatcher)(int data);
Assume that the dispatchers are like below:
int set_DhcpDispatcher(int data) { return data; }
int get_DhcpDispatcher(int data) { return 2*data; }
So, the revised structure will be:
typedef struct command {
const char *code;
genericDispatcher set_dispatcher;
genericDispatcher get_dispatcher;
const char *_description;
} command_t;
Your macro will be:
#define COMMAND_ENTRY(label,dispatcher,description) \
{ (const char*)label, \
set_##dispatcher##Dispatcher, \
get_##dispatcher##Dispatcher, \
(const char*)description }
Then, you can set your array as usual:
int main(int argc, char **argv)
{
int value1 = 0, value2 = 0;
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)")
};
value1 = commands[0].set_dispatcher(1);
value2 = commands[0].get_dispatcher(2);
printf("value1 = %d, value2 = %d", value1, value2);
return 0;
}
Correct me, if I am wrong somewhere... ;)

Resources