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);
}
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);
}
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.
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