Skip to content

Instantly share code, notes, and snippets.

@icecoobe
Created March 3, 2025 03:18
Show Gist options
  • Select an option

  • Save icecoobe/d4b80983e05164b37ed246de2e63f536 to your computer and use it in GitHub Desktop.

Select an option

Save icecoobe/d4b80983e05164b37ed246de2e63f536 to your computer and use it in GitHub Desktop.
Example: handle c-style callback in c++
#include "c_lib.h"
#include <stdio.h>
/**
* @brief func_ptr_
*/
static c_lib_func_ptr func_ptr_;
/**
* @brief c_lib_regist_func_ptr
* @param p
*/
void c_lib_regist_func_ptr(c_lib_func_ptr p)
{
func_ptr_ = p;
}
/**
* @brief c_lib_do_something
*/
void c_lib_do_something(int n)
{
printf("[%s] internal callback address: %lX, param: %04X\n",
__FUNCTION__,
(unsigned long)func_ptr_,
n);
}
#ifndef C_LIB_H_INCLUDED
#define C_LIB_H_INCLUDED
#ifdef __cplusplus
extern "C"{
#endif
typedef void (*c_lib_func_ptr)(int a);
extern void c_lib_regist_func_ptr(c_lib_func_ptr);
extern void c_lib_do_something(int n);
#ifdef __cplusplus
}
#endif
#endif
#ifndef C_LIB_WRAPPER_HPP_INCLUDED
#define C_LIB_WRAPPER_HPP_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif // #ifdef __cplusplus
#include "c_lib.h"
#ifdef __cplusplus
}
#endif // #ifdef __cplusplus
#include <iostream>
/**
* @brief The ClibWrapper class
*/
class ClibWrapper
{
public:
/**
* @brief ClibWrapper
*/
ClibWrapper()
{
regist_callback();
}
~ClibWrapper() = default;
ClibWrapper(const ClibWrapper&) = delete;
ClibWrapper(ClibWrapper&) = delete;
private:
void regist_callback()
{
static auto f = [this](int n)
{
test(n);
};
c_lib_regist_func_ptr([](int n)
{
f(n);
});
}
/**
* @brief test
* @remarks will be passed to c lib as a callback
* @param n
*/
void test(int n)
{
std::cout << __FUNCTION__ << ": " << n << std::endl;
}
};
#endif // C_LIB_WRAPPER_HPP_INCLUDED
#include "c_lib.h"
#include "c_lib_wrapper.hpp"
#include <iostream>
using namespace std;
int main()
{
ClibWrapper wrapper;
c_lib_do_something(1024);
//cout << "Hello World!" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment