Skip to content

Instantly share code, notes, and snippets.

@yeputons
Last active April 11, 2021 11:16
Show Gist options
  • Save yeputons/b4534e398842bb696921b6b118a6fd3b to your computer and use it in GitHub Desktop.
Save yeputons/b4534e398842bb696921b6b118a6fd3b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "lib.h"
double f0(void) {
return 123;
}
double f2(double a, double b) {
return a + b;
}
int main() {
cb_arity = 0;
cb_func = f0;
printf("%f\n", cb_call());
cb_arity = 2;
cb_func = f2;
printf("%f\n", cb_call());
}
#include <stdio.h>
#include "lib.h"
int main() {
cb_arity = 0;
cb_func = []() { return 123.0; };
printf("%f\n", cb_call());
cb_arity = 2;
cb_func = reinterpret_cast<double(*)()>(static_cast<double(*)(double, double)>(
[](double a, double b) { return a + b; }
));
printf("%f\n", cb_call());
}
#!/bin/bash
set -xeuo pipefail
gcc lib.c -c
gcc app_c.c lib.o -o app_c
./app_c
g++ app_cpp.cpp lib.o -o app_cpp
./app_cpp
#include "lib.h"
#include <stdlib.h>
int cb_arity;
double (*cb_func)();
double cb_call(void) {
switch (cb_arity) {
case 0:
return cb_func();
case 1:
return cb_func(10.0);
case 2:
return cb_func(10.0, 20.0);
case 3:
return cb_func(10.0, 20.0, 30.0);
default:
abort();
}
}
#ifndef LIB_H_
#define LIB_H_
#ifdef __cplusplus
extern "C" {
#endif
extern int cb_arity;
extern double (*cb_func)();
double cb_call(void);
#ifdef __cplusplus
}
#endif
#endif // LIB_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment