Skip to content

Instantly share code, notes, and snippets.

@ultimateprogramer
Forked from gaspard/gist:1087380
Last active October 27, 2022 10:23
Show Gist options
  • Save ultimateprogramer/83aeca704a904310025bbe45ba0125dd to your computer and use it in GitHub Desktop.
Save ultimateprogramer/83aeca704a904310025bbe45ba0125dd to your computer and use it in GitHub Desktop.
Simple C++ class with C interface for Luajit ffi bindings
// g++ simple.cpp -shared -o libsimple.dylib
#include <stdio.h>
class Simple {
int id_;
public:
Simple(int id);
~Simple();
int id();
};
Simple::Simple(int id) : id_(id) {
printf("[%p:%i] Simple()\n", this, id_);
}
Simple::~Simple() {
printf("[%p:%i] ~Simple()\n", this, id_);
}
int Simple::id() {
return id_;
}
extern "C" {
Simple *Simple_Simple(int id) {
return new Simple(id);
}
void Simple__gc(Simple *this_) {
delete this_;
}
int Simple_id(Simple *this_) {
return this_->id();
}
}
/* This is C code */
#include "Fred.h"
void c_function(Fred* fred)
{
cplusplus_callback_function(fred);
}
// This is C++ code
#include "Fred.h"
Fred::Fred() : a_(0) {}
void Fred::wilma(int a) {}
Fred* cplusplus_callback_function(Fred* fred)
{
fred->wilma(123);
return fred;
}
/* This header can be read by both C and C++ compilers */
#ifndef FRED_H
#define FRED_H
#ifdef __cplusplus
class Fred {
public:
Fred();
void wilma(int);
private:
int a_;
};
#else
typedef struct Fred Fred;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__STDC__) || defined(__cplusplus)
extern void c_function(Fred*); /* ANSI C prototypes */
extern Fred* cplusplus_callback_function(Fred*);
#else
extern void c_function(); /* K&R style */
extern Fred* cplusplus_callback_function();
#endif
#ifdef __cplusplus
}
#endif
#endif /*FRED_H*/
// This is C++ code
#include "Fred.h"
int main()
{
Fred fred;
c_function(&fred);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment