groenhen groenhen - 1 month ago 8
C Question

Using C++ classes in C: How to properly write some sort of "delete/dispose" function?

I just need to use C++ class(es) in C code.

Let's say the C++ class looks like this:

class MyClass
{
public:
void myFunction()
{
cout << "Value = " << m_value;
}

private:
int m_value;
};


And I wrote some wrapper like this:

typedef void CMyClass;

#ifdef __cplusplus
extern "C" {
#endif

CMyClass * new_MyClass();
void c_myFunction(const CMyClass * ptr);
void c_dispose( ??? ); // to delete/destruct
#ifdef __cplusplus
}
#endif

// implementation below:

extern "C" {

CMyClass * new_CMyClass()
{
MyClass * ptr = new MyClass();

return (CMyClass*)ptr;
}

void c_myFunction(const CMyClass * ptr)
{
MyClass * tmp = (MyClass*)ptr;
tmp->myFunction();
}

void c_dispose( ??? )
{
/* ??? */
}

}


So, finally, the question is:

How to properly write the complete code for
c_dispose(???)
to delete the previously created (with
new_CMyClass()
) object instance?... just to make sure I won't have any problems like memory leaks, zombie pointers, etc. :(

Thanks in advance for your time and patience.

Answer

A possible solution would be to simply call the delete once you casted the C type to C++ class.

void c_dispose(CMyClass * ptr){
    MyClass * tmp = (MyClass*)ptr;  
    delete tmp;
}
Comments