I am implementing a c++ class based library file. I need to link this library to both c file and c++ file. I guess, there will be no issues instantiating the class from c++ file. I do find a way to instantiate the class from c file aswell, but it seems I need to pass the object every time while a function call. Is there any way i could use the instantiated object directly in c file to call a member function?
Find the code sample below,
Myclass.h
#ifndef __MYCLASS_H
#define __MYCLASS_H
class MyClass {
private:
int m_i;
public:
void int_set(int i);
int int_get();
};
#endif
MyClass.cc
#include "MyClass.h"
void MyClass::int_set(int i) {
m_i = i;
}
int MyClass::int_get() {
return m_i;
}
MyMain_c++.cc
#include "MyClass.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
MyClass *c = new MyClass();
c->int_set(3);
cout << c->int_get() << endl;
delete c;
}
MyWrapper.h
#ifndef __MYWRAPPER_H
#define __MYWRAPPER_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct MyClass MyClass;
MyClass* newMyClass();
void MyClass_int_set(MyClass* v, int i);
int MyClass_int_get(MyClass* v);
void deleteMyClass(MyClass* v);
#ifdef __cplusplus
}
#endif
#endif
MyWrapper.cc
#include "MyClass.h"
#include "MyWrapper.h"
extern "C" {
MyClass* newMyClass() {
return new MyClass();
}
void MyClass_int_set(MyClass* v, int i) {
v->int_set(i);
}
int MyClass_int_get(MyClass* v) {
return v->int_get();
}
void deleteMyClass(MyClass* v) {
delete v;
}
}
MyMain_c.c
#include "MyWrapper.h"
#include <stdio.h>
int main(int argc, char* argv[]) {
struct MyClass* c = newMyClass();
MyClass_int_set(c, 3); // issue : i need to send the object
everytime
// c->int_set(3); any ways of using like this??
printf("%i\n", MyClass_int_get(c));
deleteMyClass(c);
}