Skip to content

Instantly share code, notes, and snippets.

@lebedov
Last active April 3, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lebedov/372ac0ffbb575c6e40f503c609a9c27f to your computer and use it in GitHub Desktop.
Save lebedov/372ac0ffbb575c6e40f503c609a9c27f to your computer and use it in GitHub Desktop.
Example of how to access a static C++ class instance from C.
Example of how to access a static C++ class instance from C.
// Compile this as a C file:
#include <stdio.h>
#include "mylib.h"
void show(int data[], int n) {
for (int i=0; i<n; i++) {
printf("%d ", data[i]);
}
printf("\n");
}
int main(void) {
// Set class attribute instance via wrapper:
int data[] = {1, 2, 3};
init(data);
// Access class attribute via pointer:
show(mydata, 3);
mydata[0] = 10;
show(mydata, 3);
}
%.o: %.c
gcc -c $<
%.o: %.cpp
g++ -c $<
main: main.o mylib.o
gcc $^ -o $@
clean:
rm -f main *.o
// Compile this as a C++ file:
#include "mylib.h"
// Since this is compiled as C++, mydata can be assigned the address of
// the static class instance's data attribute:
static MyClass myclass;
extern int *mydata = myclass.data;
// C functions:
extern "C" {
void init(int data[3]) {
myclass.set(data);
}
}
#include <stdint.h>
#include <stdlib.h>
// C++ definitions:
#ifdef __cplusplus
class MyClass {
public:
int data[3];
MyClass() { set(0); }
void set(int data[]) {
for (int i=0; i<3; i++) {
this->data[i] = data[i];
}
}
void set(int d) {
for (int i=0; i<3; i++) {
this->data[i] = d;
}
}
};
#endif
// C access points that use C++ code:
#ifdef __cplusplus
extern "C" {
#endif
// mydata is set in mylib.cpp:
extern int *mydata;
void init(int data[3]);
#ifdef __cplusplus
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment