How to get pointer address in function that called through this pointer - c

I read this article but it doesn't answer my question.
file: hero.h
typedef struct {
int id;
void (*setId)();
int (*getId)();
} Hero, *HeroPtr;
file: hero.c
#include "hero.h"
static void setId(int id);
Hero obj = {
.setId = setId,
.getId = getId,
};
void setId(int id) {
HeroPtr hero_obj = 0x0; //TODO how get address: hero_obj1 (1 > ) OR
// hero_obj2 (2 > )
hero_obj->id = id;
}
void getId() {
HeroPtr hero_obj = 0x0; //TODO how get address: hero_obj1 (1 > ) OR
// hero_obj2 (2 > )
return hero_obj->id;
}
file: main.c
#include "hero.h"
int main() {
Hero hero_obj1, hero_obj2;
//1 >
hero_obj1->setId(1);
//2 >
hero_obj2->setId(2);
return 0;
}

You could do the equivalent of what C++ does behind the scenes.
file: hero.h
typedef struct hero {
int id;
void (*setId)(struct hero*, int);
int (*getId)(struct hero*);
} Hero, *HeroPtr;
void constructHero(HeroPtr this);
file: hero.c
#include "hero.h"
static void setId(HeroPtr this, int id);
static int getId(HeroPtr this);
Hero initObj = {
.setId = &setId,
.getId = &getId,
};
void constructHero(HeroPtr this)
{
*this = initObj;
}
void setId(HeroPtr this, int id) {
HeroPtr hero_obj = this;
hero_obj->id = id;
}
int getId(HeroPtr this) {
HeroPtr hero_obj = this;
return hero_obj->id;
}
file: main.c
#include "hero.h"
#include "stdio.h"
int main() {
Hero hero1;
Hero hero2;
HeroPtr hero_obj1=&hero1;
HeroPtr hero_obj2=&hero2;
constructHero(hero_obj1);
constructHero(hero_obj2);
hero_obj1->setId(hero_obj1, 1);
hero_obj2->setId(hero_obj2, 2);
printf("hero_obj1 id = %d\n", hero_obj1->getId(hero_obj1));
printf("hero_obj2 id = %d\n", hero_obj2->getId(hero_obj2));
return 0;
}

It looks like you are trying to implement virtual functions in C, by using function pointers. In object-oriented programming languages like C++ or Java such functions or methods inside classes have an implicit this pointer as argument, which is hidden. That means that the int getId() function actually has the signature int getId(Hero* this) and the void setId(int id) function actually has the form void setId(Hero* this, int id). As I have already said, in object-oriented programming languages you don't see or add the this pointer and you also don't pass the argument when you invoke the function. The compiler does this for you. It always automatically passes the pointer to the instance as this pointer, on which the function was invoked. In C, however, these features don't exist. So you have to add the this argument and pass it when invoking the function by yourself.

Related

Wrap C++ class for C API

I have a shared library written in C++ that i need to expose for C as well.
Let's say i have to wrap the following class :
class Foo
{
public:
const std::vector<int> &getList() const
{
return m_list;
}
private:
std::vector<int> m_list {0, 1, 2, 3, 4};
};
First wrapper version :
struct wrap_foo
{
Foo m_f;
};
typedef struct wrap_foo *wrap_foo_t;
const int *getList(wrap_foo_t f) // useful ?
{
return f->m_f.getList().data();
}
int listSize(wrap_foo_t f)
{
return f->m_f.getList().size();
}
int getVal(wrap_foo_t f, int i)
{
return f->m_f.getList().at(i);
}
wrap_foo_t createFoo()
{
return new wrap_foo;
}
void cleanFoo(wrap_foo_t f)
{
delete f;
}
2nd wrapper version :
struct vec
{
const int *first;
int size; // number of elements
};
typedef struct vec *vec_t;
vec_t getList2(wrap_foo_t f)
{
vec_t v = new vec;
v->first = f->m_f.getList().data();
v->size = f->m_f.getList().size();
return v;
}
int getVal2(vec_t v, int i)
{
return *(v->first + i);
}
void cleanVec(vec_t v)
{
delete v;
}
For the first version, the C client code would then use the C API in this way :
wrap_foo_t wf = createFoo();
for (int i = 0; i < listSize(wf); i++)
printf("v = %d\n", getVal(wf, i));
cleanFoo(wf);
And in the 2nd version :
wrap_foo_t wf2 = createFoo();
vec_t list = getList2(wf2);
for (int i = 0; i < list->size; i++)
printf("v = %d\n", getVal2(list, i));
cleanVec(list);
cleanFoo(wf2);
The internal list is wrapped into a c structure in the second version, keeping its size. In the first version, each time the class is extended (for example by adding other getList methods, getList1, getList2,..), 2 wrappers functions are needed (one to return a pointer, one to return the size).
Is there a better choice to wrap this class ?
(except from errors that are not handled in this small example here)
Thank you.

How do I check the call order of different functions in C

in order to set a certain variable (MyVariable) to "TRUE" I have to check that a specific function call order was respected within a system.
For example, I have different functions within the system:
uint8 myFunction1()
{
if (...)
{
return NOT_OK
}
else
{
return OK
}
}
uint8 myFunction2()
{
if (...)
{
return NOT_OK
}
else
{
return OK
}
}
uint8 myFunction3()
{
if (...)
{
return NOT_OK
}
else
{
return OK
}
}
MyVariable = TRUE only if:
OK == myFunction1
OK == myFunction2
OK == myFunction3
exactly this call order was respected.
How to check the call order in C but without touching the body of the functions (like setting some flags´etc.)?
I'm still beginner and experimenting with C :)
Thanks!
This is almost certainly an "XY problem". That is, you think saving the call order is the solution to your actual problem, but your actual problem might be to ensure that the functions can't be called in the wrong order in the first place.
So the most correct way to fix this is to remake the program design. Someone mentioned state machines as one solution. Another solution might be something like an array of function pointers (which is a common implementation of state machines).
That being said, you can do something artificial to track the call order, though I wouldn't really recommend it. Example:
#define CALL_ORDER_N 3
const char* call_order [CALL_ORDER_N] = {NULL};
size_t call_order_i = 0;
static void save_call (const char* func)
{
call_order[call_order_i] = func;
call_order_i++;
if(call_order_i == CALL_ORDER_N)
{
call_order_i = 0;
}
}
Where call_order saves the 3 last function calls as pointers to string literals. The function save_call updates this array, by passing the __func__ constant to it from each function. __func__ is guaranteed to work like a static const char[] so this is safe. You'd do something like this:
void myFunction1 (void)
{
save_call(__func__);
...
}
void myFunction2 (void)
{
save_call(__func__);
...
}
void myFunction3 (void)
{
save_call(__func__);
...
}
And then go through the calls to see if they were in the correct order:
static bool is_call_order_ok (void)
{
const char* expected_order [CALL_ORDER_N] =
{
"myFunction1",
"myFunction2",
"myFunction3"
};
size_t co_i = call_order_i;
for(size_t i=0; i<CALL_ORDER_N; i++)
{
if(strcmp(call_order[co_i], expected_order[i])==0)
{
co_i++;
if(co_i == CALL_ORDER_N)
{
co_i = 0;
}
}
else
{
return false;
}
}
return true;
}
Full example:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define CALL_ORDER_N 3
const char* call_order [CALL_ORDER_N] = {NULL};
size_t call_order_i = 0;
static void save_call (const char* func)
{
call_order[call_order_i] = func;
call_order_i++;
if(call_order_i == CALL_ORDER_N)
{
call_order_i = 0;
}
}
static bool is_call_order_ok (void)
{
const char* expected_order [CALL_ORDER_N] =
{
"myFunction1",
"myFunction2",
"myFunction3"
};
size_t co_i = call_order_i;
for(size_t i=0; i<CALL_ORDER_N; i++)
{
if(strcmp(call_order[co_i], expected_order[i])==0)
{
co_i++;
if(co_i == CALL_ORDER_N)
{
co_i = 0;
}
}
else
{
return false;
}
}
return true;
}
void myFunction1 (void)
{
save_call(__func__);
}
void myFunction2 (void)
{
save_call(__func__);
}
void myFunction3 (void)
{
save_call(__func__);
}
int main (void)
{
printf("Call 1,2,3: ");
myFunction1();
myFunction2();
myFunction3();
printf(is_call_order_ok() ? "Ok\n" : "Failed\n");
printf("Call 3,2,1: ");
myFunction3();
myFunction2();
myFunction1();
printf(is_call_order_ok() ? "Ok\n" : "Failed\n");
printf("Call 1,1,1: ");
myFunction1();
myFunction1();
myFunction1();
printf(is_call_order_ok() ? "Ok\n" : "Failed\n");
return 0;
}
The advanced, more professional version of the above, would be to cook together a mini-API with a single function, in order to give private encapsulation to every single variable. The function save_call would then be a multi-purpose function, that can be used to register expected call order, save function calls, as well as verify if the current registered order is ok.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define CALL_ORDER_N 3
static bool save_call (const char* func, bool verify)
{
bool result;
static const char* call_order [CALL_ORDER_N] = {NULL};
static size_t call_order_i = 0;
static const char* expected_order [CALL_ORDER_N] = {NULL};
size_t i = call_order_i;
if(verify) // special case, verify the order
{
for(size_t expected=0; expected<CALL_ORDER_N; expected++)
{
if(call_order[i] == expected_order[expected])
{
i++;
if(i == CALL_ORDER_N)
{
i = 0;
}
}
else
{
return false;
}
}
return true;
}
if(expected_order[i] == NULL) // register order of calls
{
expected_order[i] = func;
result = true;
}
else // save calls
{
call_order[i] = func;
result = false;
}
call_order_i++;
if(call_order_i == CALL_ORDER_N)
{
call_order_i = 0;
}
return result;
}
void myFunction1 (void)
{
if(save_call(__func__, false))
return ;
printf("Execute stuff in %s.\n", __func__);
}
void myFunction2 (void)
{
if(save_call(__func__, false))
return ;
printf("Execute stuff in %s.\n", __func__);
}
void myFunction3 (void)
{
if(save_call(__func__, false))
return ;
printf("Execute stuff in %s.\n", __func__);
}
int main (void)
{
/* register call order: */
myFunction1();
myFunction2();
myFunction3();
printf("Call 1,2,3:\n");
myFunction1();
myFunction2();
myFunction3();
printf(save_call(NULL, true) ? "Ok\n\n" : "Failed\n\n");
printf("Call 3,2,1:\n");
myFunction3();
myFunction2();
myFunction1();
printf(save_call(NULL, true) ? "Ok\n\n" : "Failed\n\n");
printf("Call 1,1,1:\n");
myFunction1();
myFunction1();
myFunction1();
printf(save_call(NULL, true) ? "Ok\n\n" : "Failed\n\n");
return 0;
}
save_call should of course be properly placed in a .h/.c file pair of its own.
There is no direct and portable way. That being said, debuggers are great at breaking execution flow when a function is reached, so you could either use a debugger, or use debugging functions to be warned when the functions are called (unfortunately nothing portable here).
Alternatively, some linkers allow to hide some identifiers and replace them so with custom (and advanced) link options you could replace all call to those functions with calls to custom wrappers. But here again it would only makes sense for a specific implementation so it is not a C way either.
Anyway, this is such an uncommon requirement that I cannot imagine the actual reasonning behind. Maybe you could give more context about your real problem...

How to return a new object created in node native code via asynchronous callback?

I am trying to create a node addon that does something like this:
// js
addon.makeObject((err, obj) => {
if (err) { /* handle error */ }
console.log('New object ID=%d', obj.getID());
:
});
The makeObject() is sort of an "asynchronous object factory" where a new instance is created inside the native C++ code in the background (using Nan::AsyncWorker) with necessary setups then returned back to NodeJS land via callback.
Here's a snippet of the native code:
// cpp
#include <nan.h>
#ifndef _WIN32
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
class MyClass : public Nan::ObjectWrap {
public:
class Worker : public Nan::AsyncWorker {
public:
friend class MyClass;
explicit Worker(Nan::Callback* callback) : Nan::AsyncWorker(callback) {}
private:
virtual void Execute() {/* some long running task */ Sleep(1000); }
virtual void HandleOKCallback() {
MyClass *mc = new MyClass();
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
mc->Wrap(obj); // ==> Assertion failed: (object->InternalFieldCount() > 0)
v8::Local<v8::Value> argv[] = { Nan::Undefined(), obj };
callback->Call(2, argv);
}
};
explicit MyClass() : _id(idCtr++) {}
~MyClass() {}
static void Init(v8::Local<v8::Object> exports) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("MyClass").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "getID", GetID);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("MyClass").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
private:
int _id;
static Nan::Persistent<v8::Function> constructor;
static NAN_METHOD(New) {
if (info.IsConstructCall()) {
MyClass* mc = new MyClass();
mc->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
const int argc = 0;
v8::Local<v8::Value> argv[argc] = {};
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
}
static NAN_METHOD(GetID) {
MyClass *mc = ObjectWrap::Unwrap<MyClass>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Integer>(mc->_id));
}
static int idCtr;
};
Nan::Persistent<v8::Function> MyClass::constructor;
int MyClass::idCtr = 0;
NAN_METHOD(MakeObject) {
// Check arguments here...
Nan::Callback *cb = new Nan::Callback(info[0].As<v8::Function>());
Nan::AsyncQueueWorker(new MyClass::Worker(cb)); // starts the worker
info.GetReturnValue().Set(Nan::Undefined());
}
void InitAll(v8::Local<v8::Object> exports) {
exports->Set( Nan::New("makeObject").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(MakeObject)->GetFunction());
MyClass::Init(exports);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
Although this compiles, it fails at this line:
mc->Wrap(obj);
This is the error:
Assertion failed: (object->InternalFieldCount() > 0), function Wrap, file ../node_modules/nan/nan_object_wrap.h, line 55.
What is InternalFieldCount? I've been googling to find a way but with no luck so far...
I found an answer myself. The key was to use Nan::NewInstance on a constructor - the same way to handle JS code calling constructor as a normal function.
Here's the complete code that works:
// addon.cpp
#include <nan.h>
#ifndef _WIN32
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
class MyClass : public Nan::ObjectWrap {
public:
class Worker : public Nan::AsyncWorker {
public:
friend class MyClass;
explicit Worker(Nan::Callback* callback) : Nan::AsyncWorker(callback) {}
private:
virtual void Execute() {/* some long running task */ Sleep(1000); }
virtual void HandleOKCallback() {
///////////////////////////////////////////////////////////
// Create MyClass instance and pass it to JS via callback
const int argc = 0;
v8::Local<v8::Value> argv[argc] = {};
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
v8::Local<v8::Object> obj = Nan::NewInstance(cons, argc, argv).ToLocalChecked();
v8::Local<v8::Value> _argv[] = { Nan::Undefined(), obj };
callback->Call(2, _argv);
}
};
explicit MyClass() : _id(idCtr++) {}
~MyClass() {}
static NAN_MODULE_INIT(Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("MyClass").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "getID", GetID);
constructor.Reset(tpl->GetFunction());
target->Set(Nan::New("MyClass").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
private:
int _id;
static Nan::Persistent<v8::Function> constructor;
static NAN_METHOD(New) {
if (info.IsConstructCall()) {
MyClass* mc = new MyClass();
mc->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
const int argc = 0;
v8::Local<v8::Value> argv[argc] = {};
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
}
static NAN_METHOD(GetID) {
MyClass *mc = ObjectWrap::Unwrap<MyClass>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Integer>(mc->_id));
}
static int idCtr;
};
Nan::Persistent<v8::Function> MyClass::constructor;
int MyClass::idCtr = 0;
NAN_METHOD(MakeObject) {
// Check arguments here...
Nan::Callback *cb = new Nan::Callback(info[0].As<v8::Function>());
Nan::AsyncQueueWorker(new MyClass::Worker(cb)); // starts the worker
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_MODULE_INIT(InitAll) {
target->Set( Nan::New("makeObject").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(MakeObject)->GetFunction());
MyClass::Init(target);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

How to implement a stack containing function call for a PIC in C

I'm currently programming a PIC in C with MPLAB X (+ compiler XC8)
In my code, I have some interruptions (inter1, inter2, ..) which are each composed of urgent and non-urgent operations (urg1, urg2, .., n_urg1, n_urg2, ..).
So I'd like a code with the following structure :
stack s; // FIFO or other
main() {
while (true) {
if (!isEmpty(s)) {
doNextFunction(s);
}
}
}
void interrupt inter1() {
urg1(); // urgent code
addStack(n_urg1);
}
void n_urg1() {
// non-urgent code
}
How can I implement that kind of stack ? Is there something in the standard library ?
If I remember correct, then that compiler is rather primitive, I don't think you can use the std library.
If you need to implement it all by yourself, you can use an array of function pointers:
#include <string.h> // for memmove()
#define STACK_MAX 10
typedef enum
{
Int,
Boolean
} VariantType;
typedef struct
{
VariantType type;
union {
int intValue;
bool booleanValue;
} value;
} Variant;
typedef bool (*FunctionPtr)(Variant data);
typedef struct
{
FunctionPtr ptr;
Variant var;
} FunctionCall;
FunctionCall functionStack[STACK_MAX];
int functionStackUse = 0;
bool addStack(FunctionPtr ptr, Variant var)
{
if (functionStackUse >= STACK_MAX)
return false; // stack full
functionStack[functionStackUse].ptr = ptr;
functionStack[functionStackUse].var = var;
functionStackUse++;
return true;
}
bool callNextFunction(void)
{
// TODO: disable inter1
if (functionStackUse > 0)
{
// get first function on stack
FunctionCall functionCall = functionStack[0];
functionStackUse--;
// remove first function from stack
memmove((void*)functionStack, (void*)(functionStack + 1), functionStackUse * sizeof(functionStack[0]));
// TODO: re-enable inter1
// call function with arguments
return (*functionCall.ptr)(functionCall.var);
}
else
{
// TODO: re-enable inter1
return false; // no more functions
}
}
void main()
{
while (1)
{
callNextFunction();
// TODO add some delay otherwise you're constantly disabling inter1 (in doNextFunction)
}
}
bool n_urg1(Variant var)
{
if (var.type == Int)
{
int i = var.value.intValue;
// do something
return true;
}
return false;
}
void inter1(void)
{
Variant var;
var.type = Int;
var.value.intValue = 45;
addStack(n_urg1, var);
}

How can I store a function pointer in a structure?

I have declared typedef void (*DoRunTimeChecks)();
How do I store that as a field in a struct? How do I assign it? How do I call the fn()?
Just put it in like you would any other field:
struct example {
int x;
DoRunTimeChecks y;
};
void Function(void)
{
}
struct example anExample = { 12, Function };
To assign to the field:
anExample.y = Function;
To call the function:
anExample.y();
#include <stdio.h>
typedef void (*DoRunTimeChecks)();
struct func_struct {
DoRunTimeChecks func;
};
void function()
{
puts("hello");
}
int main()
{
struct func_struct func_struct;
func_struct.func = function;
func_struct.func();
return 0;
}

Resources