Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C++ class method without a class instance?

Long story short, I am trying to build a wrapper to access C++ source code from a C main function (I have to do the conversion because of Embedded systems); however, I am having trouble calling the methods from the class to an external function without creating an instance of that class.

I want to pass this *side pointer from my C code, calculate the cube of it, and get returned the cubed value. I have tested my wrapper with simple pointer functions and variables and it works perfectly fine, however I am having trouble with class methods. Here is my source code to that, with the mistake I am making on the last line...:

class Cube
{
public:
    static int getVolume(int *side)
    {
        return *side * *side * *side;     //returns volume of cube
    }
};

void Cube_C(int *side) 
{
    return Cube.getVolume(*side);
}
like image 318
Polar Bear Avatar asked Dec 06 '25 10:12

Polar Bear


2 Answers

You can call a static member function of a class without an instance: just add the class name followed by the scope resolution operator (::) before the member function's name (rather than the class member operator, ., as you have tried).

Also, in your Cube_C function, you should not dereference the side pointer, as the getVolume function takes a int * pointer as its argument. And you need to declare the return type of that function as an int (not void):

int Cube_C(int *side) 
{
    return Cube::getVolume(side);
}
like image 66
Adrian Mole Avatar answered Dec 09 '25 00:12

Adrian Mole


For this particular example, you don't need them to be classes at all since Cube doesn't hold a state. Just make a function:

int Cube_Volume(int side) { return side * side * side; }

If you want objects that holds a state to be reusable from C, you do need an instance:

class Cube {
public:
    Cube(int side) : m_side(side) {}
    int getVolume() const { return m_side * m_side * m_side; }

private:
    int m_side;
};

Then in your C interface:

extern "C" int Cube_Volume(int side) { return Cube(side).getVolume(); }

Edit: I added a more verbose example at github to show how you can create C functions to create and manipulate C++ objects.

like image 43
Ted Lyngmo Avatar answered Dec 08 '25 22:12

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!