Results 1 to 1 of 1
Hello everyone,
I was looking for a solution to include C++ objects into a C executable...I couldn't find anything on the internet so I came up with this solution. It ...
- 08-15-2008 #1
including C++ objects in a C executable
Hello everyone,
I was looking for a solution to include C++ objects into a C executable...I couldn't find anything on the internet so I came up with this solution. It works O.K. but I was wondering has anyone else come across this problem and what was their solution...
My solution is to create C wrapper functions around the C++ object methods and to include the C++ standard libraries in the C compile line.
I included a simple example below, so you can see where I'm going with this....so my question is...is this the best/simplest way to include C++ objects in a C executable?
myclass.cpp
class myint
{
public:
myint() {}
~myint() {}
int getitsvalue() const {return itsvalue;}
void setitsvalue(int x) {itsvalue = x;}
private:
int itsvalue;
};
extern "C" void* creatit()
{
myint* theint = new myint();
return (void*)theint;
}
extern "C" void destroyit(void* val)
{
delete (myint*)val;
}
extern "C" int getit(void* val)
{
return ((myint*)val)->getitsvalue();
}
extern "C" void setit(void* val, int x)
{
((myint*)val)->setitsvalue(x);
}
test.c
#include <stdio.h>
#include <stdlib.h>
extern void* creatit();
extern void destroyit(void* val);
extern int getit(void* val);
extern void setit(void* val, int x);
int main(int argc, char**argv)
{
void* mytest = creatit();
setit(mytest, 1234);
int ans = getit(mytest);
fprintf(stdout, "ans->%d\n", ans);
destroyit((void*)mytest);
exit(EXIT_SUCCESS);
}
makfile
test: test.o myclass.o
gcc test.o myclass.o -o test -lstdc++
test.o: test.c
gcc -c test.c
myclass.o: myclass.cpp
g++ -c myclass.cpp


Reply With Quote