Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ can I pass a structure as a pointer without declaring it locally?

Tags:

c++

sdl

I'm working with SDL which is a C library that has declarations of functions like this:

void SDL_foo(SDL_Rect *rect);

I have my own wrappers around some of the functions like this:

void foo(SDL_Rect rect) {
  SDL_foo(&rect);
}

This is so I can simply call them like this:

foo({x, y, w, h});

My question is: is it possible to avoid having a wrapper function and do something like this:

SDL_foo(&{x, y, w, h});

Thanks!

like image 701
Kristopher Ives Avatar asked Jun 22 '18 04:06

Kristopher Ives


People also ask

Is it possible to declare function pointer in structure yes or no?

You can only define a function pointer in a struct in C programming language which is different from C++.

Can a structure be declared locally?

The struct definition must be known to both the calling and called functions, which means it is must be defined globally. However the actual struct variables should still be declared locally, just like any other variables.

How is a structure type pointer variable declared?

The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can declare the structure pointer and variable inside and outside of the main() function. To declare a pointer variable in C, we use the asterisk (*) symbol before the variable's name.


1 Answers

No, you cannot do that because you can't get the address of a temporary.
But you can probably get away with it with a kind of wrapper like this:

struct MyRect {
    MyRect(SDL_rect rect): rect{rect} {}
    operator SDL_rect *() { return ▭ }
    SDL_rect rect;
};

SDL_foo(MyRect{{x, y, w, h}});

Not tested yet, but it should give you an idea of what I mean.
This way, instead of creating wrappers for all the functions from SDL, you have to create only a tiny wrapper around SDL_rect.
Not sure if it works fine for you anyway.

like image 168
skypjack Avatar answered Oct 26 '22 17:10

skypjack