简体   繁体   English

在没有 class 实例的情况下调用 C++ class 方法?

[英]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);长话短说,我正在尝试构建一个包装器以从 C main function 访问 C++ 源代码(由于嵌入式系统,我必须进行转换); however, I am having trouble calling the methods from the class to an external function without creating an instance of that class.但是,我无法在不创建该 class 实例的情况下将方法从 class 调用到外部 function。

I want to pass this *side pointer from my C code, calculate the cube of it, and get returned the cubed value.我想从我的 C 代码中传递这个*side指针,计算它的立方,并返回立方值。 I have tested my wrapper with simple pointer functions and variables and it works perfectly fine, however I am having trouble with class methods.我已经用简单的指针函数和变量测试了我的包装器,它工作得很好,但是我在使用 class 方法时遇到了问题。 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).您可以在没有实例的情况下调用 class 的static成员 function:只需在成员函数名称之前添加 class 名称,然后添加scope 解析运算符( :: )(而不是 class,作为成员运算符) .

Also, in your Cube_C function, you should not dereference the side pointer, as the getVolume function takes a int * pointer as its argument.此外,在您的Cube_C function 中,您不应取消引用side指针,因为getVolume function 将int *指针作为其参数。 And you need to declare the return type of that function as an int (not void ):并且您需要将 function 的返回类型声明为int (不是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:对于这个特定的示例,您根本不需要它们是类,因为Cube不包含 state。只需创建一个 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:如果您希望包含 state 的对象可从 C 重用,您确实需要一个实例:

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:然后在你的C界面:

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.编辑:我在github添加了一个更详细的示例,以展示如何创建 C 函数来创建和操作 C++ 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM