CKTIS / C
Callback in C: puntatori a funzione con `typedef`
Dai un nome a un tipo puntatore a funzione per passare strategie e predicati, restituire una funzione scelta o memorizzare callback in strutture e array.
Versione: ISO C23; implementation support may vary
Sintassi
typedef double (*PricingFn)(double);
typedef double PricingFunc(double); /* PricingFunc * is equivalent to PricingFn */
typedef struct Order Order;
typedef int (*OrderPred)(const Order *);
typedef int (*OrderCmp)(const Order *, const Order *);
double add_fee(double);
double double_price(double);
double apply_price(double base, PricingFn fn);
PricingFn select_rule(int use_double);
void apply_rules(PricingFn rules[], size_t n); /* include <stddef.h> for size_t */
typedef struct {
PricingFn price;
} InvoiceProcessor;
/* Inside a function, with add_fee and double_price declared: */
PricingFn fn = add_fee;
PricingFn rules[] = {add_fee, &double_price};
InvoiceProcessor processor = {fn};typedef double (*PricingFn)(double); dà il nome PricingFn al tipo puntatore a una funzione che accetta un double e restituisce un double. È un alias, non un nuovo tipo né una funzione. Le parentesi attorno a *PricingFn sono importanti. Invece typedef double PricingFunc(double); dà un nome al tipo di funzione; PricingFunc * equivale a PricingFn.
In PricingFn fn = add_fee; e nel passaggio come argomento, il nome di funzione add_fee viene convertito in puntatore; va bene anche &add_fee. fn(base) e (*fn)(base) effettuano la stessa chiamata indiretta. Una funzione di selezione può restituire un PricingFn senza chiamare la funzione scelta. In seguito puoi sostituire il puntatore in una variabile oppure memorizzarlo in un campo di una struttura e chiamare p->price(base).
PricingFn rules[] può dichiarare un array di puntatori a funzione; rules[i](base) chiama la funzione all’indice i. Nella dichiarazione di un parametro, PricingFn rules[] viene adattato a PricingFn *: passa la lunghezza separatamente e rispetta i limiti dell’array. Per un array dinamico di n > 0 elementi usa PricingFn *items = malloc(n * sizeof *items); con <stdlib.h> dopo aver controllato che il prodotto sia rappresentabile in size_t. Gestisci NULL, assegna un puntatore valido a ogni posizione usata e alla fine chiama free(items). Così liberi l’array, non le funzioni.
OrderPred accetta un const Order *: zero indica falso, un valore diverso da zero indica vero. Con un predicato valido, count_if chiama pred(&orders[i]) una volta per elemento. OrderCmp accetta due const Order *; di solito un comparatore restituisce un valore negativo, zero o un valore positivo se il primo elemento è rispettivamente minore, uguale o maggiore del secondo.
Effettua chiamate solo tramite un puntatore inizializzato e non nullo a una funzione con tipi dei parametri e di ritorno compatibili. Chiamare tramite NULL o tramite un puntatore a un tipo di funzione incompatibile comporta un comportamento indefinito; un cast non risolve l’incompatibilità. void * non è un sostituto portabile di un puntatore a funzione. Questi costrutti precedono ISO C23; il supporto della modalità C23 dipende dall’implementazione.
Esempi
#include <stdio.h>
typedef double (*PricingFn)(double);
typedef struct {
int total;
} Order;
typedef int (*OrderPred)(const Order *);
typedef struct {
PricingFn price;
} InvoiceProcessor;
static double add_fee(double base) { return base + 2.0; }
static double double_price(double base) { return base * 2.0; }
static int is_large(const Order *order) { return order->total >= 10; }
static double apply_price(double base, PricingFn fn)
{
return fn(base); /* Caller must supply a valid callback. */
}
static PricingFn select_rule(int use_double)
{
return use_double ? double_price : add_fee;
}
static size_t count_if(const Order orders[], size_t n, OrderPred pred)
{
size_t matches = 0;
if (pred == NULL)
return 0;
for (size_t i = 0; i < n; ++i)
if (pred(&orders[i]))
++matches;
return matches;
}
int main(void)
{
PricingFn fn = select_rule(0);
printf("strategy: %.0f\n", apply_price(10.0, fn));
PricingFn rules[] = {add_fee, &double_price};
fn = rules[1];
InvoiceProcessor processor = {fn};
const InvoiceProcessor *p = &processor;
printf("switched: %.0f\n", p->price(10.0));
const Order orders[] = {{7}, {10}, {24}};
printf("matches: %zu\n",
count_if(orders, sizeof orders / sizeof orders[0], is_large));
return 0;
}
Risultato
strategy: 12 switched: 20 matches: 2
`select_rule(0)` sceglie `add_fee`. Poi `rules[1]` fornisce `double_price`, chiamata tramite un campo della struttura. `count_if` trova due ordini che soddisfano il predicato; in questo esempio, se il predicato manca (`NULL`), il conteggio è zero.
Lezioni correlate
- C · Lezione 39 · Intermedio · Versione: 3
- C · Lezione 40 · Intermedio · Versione: 3
- C · Lezione 41 · Intermedio · Versione: 3
- C · Lezione 42 · Intermedio · Versione: 3
- C · Lezione 43 · Intermedio · Versione: 3
- C · Lezione 44 · Intermedio · Versione: 3
- C · Lezione 45 · Intermedio · Versione: 3
- C · Lezione 47 · Intermedio · Versione: 3
- C · Lezione 48 · Intermedio · Versione: 3