Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22040

Anonymous functions return dynamically allocated values

$
0
0

The question is based on a design pattern solution easily doable in other languages but difficult to implement in C. The narrowed down code is below.

Building on this answer, I'm trying to find a solution for the dynamically generated values in an anonymous function.

Excerpt from the answer:

int (*max)(int, int) =
({
    int __fn__ (int x, int y) { return x > y ? x : y; }
    __fn__;
});

Static Library Code

struct Super{
}

void add(struct Super *(*superRef)()) {
    // cache the reference (in some linked list)

    // later at some point when an event occurs.
    struct Super *super = superRef(); // instantiate and use it.
}

Client Code linked: User of the Library Code

struct Sub{
     struct Super *super;
}

add(({
    struct Sub __fn__() { return malloc(sizeof(struct Sub)); } // error
    __fn__;
}));

Error:

error: passing 'void' to parameter of incompatible type 'struct Sub *(*)()

As per the request for clarification, think of the receiving function in a static library file receiving references to the structure objects (non-instantiated). The lib receives this object from the client code.

Secondly the client or static library library doesn't instantiate the received structure reference right away. Later when there's a notification in the system, the structure reference is called to instantiate and execute the rest of the stuff.

I repeat, the specific requirement is to hold non-instantiated references to the structures passed by users of the library (client code).

Summary

Basically a Runner that receives pointer to a polymorphic factory method which it caches and later calls to instantiate and executes when an event occurs.


Viewing all articles
Browse latest Browse all 22040

Trending Articles