0

in C++ it's possible to pass a pointer from a function (above main() tree) to a class and have the class operate the function, the keyword "using" is used.

class Animation
{
public:
using FunctionPtr = void (*)(int x, int y, const Surface& s);

FunctionPtr DrawPointer;
...
..
.
}

in that same class, i can operate the function lower down in the three, above "main()".

void Animation::Draw(const Vei2 &pos) const{
    
    RectI temp = frames[iCurrentFrame];

    assert(DrawPointer == nullptr);
    //assert(DrawPointer == nullptr && "no pointer for drawing");
    if (DrawPointer2!= nullptr)
    {
        DrawPointer2(pos.x,pos.y,frames[iCurrentFrame], screensize, sprite); // function above main();
    }
    else{
        //assert(std::cout << "no pointer for drawing.\n" );
    }
}

can that be done also in C?

NaturalDemon
  • 934
  • 1
  • 9
  • 21

1 Answers1

0

In C you can create a typedef for a function pointer:

typedef void (*foo_type)(int);

And if you have a function which matches that type:

void foo(int x)
{
    printf("x=%d\n", x);
}

You can assign a pointer to that function to a variable of that type and call it through the function pointer:

foo_type f = foo;
f(5);

Or pass it to another function that could use it:

void bar(foo_type f, int arg)
{
    f(arg);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • i wanna assign a address of a MCU's peripheral to a class, but the class has to be able to talk with a function above the main loop. will check your answer tommorow, if that works. – NaturalDemon Dec 10 '22 at 03:01
  • How do i make a function in a header file in an Arduino project point to a function above the "void main()" loop, i can't use serial.println("..."); from a function defined in a header file. i made a function in the header file that accepts a char array and returns this. – NaturalDemon Dec 11 '22 at 13:35