I know that this is not a good way of developing of a project, but for some reasons of my work I am committed to integrate some data structures in C++ (LRU cache and hash map) in a C project.
So far I know that there is some way to call C functions in C++ using extern "C"
, but what about calling C++ objects (methods...) from C?
I am using GCC.
The C Programming language has many data structures like an array, stack, queue, linked list, tree, etc. A programmer selects an appropriate data structure and uses it according to their convenience.
In this Data Structures and Algorithms Through C In Depth course, C language programs are used for implementing various concepts, but you can easily code them in any other programming languages like C++, C#, Java, Python.
If all the code is being compiled with C++ compiler there should be no (or very little) problem.
If you have C compiled with gcc and C++ compiled with g++ then you need to write a header wrapper around your class to make the C++ code visable via a set of functions.
Example:
MyClass.h
#ifdef __cplusplus
class MyClass
{
public:
MyClass() {/*STUFF*/}
~MyClass() {/*STUFF*/}
int doStuff(int x, float y) {/*STUFF*/}
};
extern "C" {
#endif
/* C Interface to MyClass */
void* createMyClass();
void destroyMyClass(void* mc);
int doStuffMyClass(void* mc, int x, float y);
#ifdef __cplusplus
}
#endif
Source File
MyClass.cpp
#include "MyClass.h"
void* createMyClass() {return reinterpret_cast<void*>(new MyClass);}
void destroyMyClass(void* mc) {delete reinterpret_cast<MyClass*>(mc);}
int doStuffMyClass(void* mc, int x, float y)
{
return reinterpret_cast<MyClass*>(mc)->doStuff(x,y);
}
Your C code now just include "MyClass.h" and uses the C functions provided.
MyCFile.c
#include "MyClass.h"
int main()
{
void* myClass = createMyClass();
int value = doStuffMyClass(myClass, 5, 6.0);
destroyMyClass(myClass);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With