How do I access a class variable from an extern "C" function?

This is my basic code:

Here's the header file:

/** Include the necessary things **/

Class MyClass{
    private:
        std::string mystring;
    /**
     * Declare constructor, methods, yada yada yada
     **/
};

And here's the source file:

MyClass::MyClass(){
    mystring[0] = 0;
}

extern "C" MyClass::function(/* variables */){
    cerr << mystring << endl;
}

The problem, it seems, is that I get a segmentation fault on the cerr << mystring << endl; line. function() needs to be an extern "C" function because it's passed as an argument to a native C function.

Any ideas? Thanks in advance.

Upvotes: 1

Views: 1220

Answers (1)

cdhowie
cdhowie

Reputation: 169211

Making a class member extern "C" is of limited usefulness, and I would suggest avoiding this method of exposing a C++ method to C code.

What you should do instead is create a wrapper function that takes a pointer to an instance of MyClass as an additional argument, and does the desired invocation:

extern "C" void MyClass_function(MyClass *obj, /* variables */) {
    obj->function(/* variables */);
}

Upvotes: 1

Related Questions