简体   繁体   English

在同一个项目的C函数中调用C ++类方法

[英]Call C++ class method in a C function on same project

i have a Qt Gui project that formed mixed-language with C and C++. 我有一个Qt Gui项目,它与C和C ++形成混合语言。 I must use a C++ class function in my C source. 我必须在我的C源代码中使用C ++类函数。 How to call it? 怎么称呼它? Can u help me? 你能帮我吗?

C++ function to call 调用C ++函数

 void MainWindow::putsDisplay(int Line, char *string)
{
    if(Line == 0)
    {
        ui->customerLine_1->setPlainText(string);
    }

    if(Line == 1)
    {
        ui->customerLine_2->setPlainText(string);
    }

    if(Line == 2)
    {
        ui->cashierLine_1->setPlainText(string);
    }

    if(Line == 3)
    {
        ui->cashierLine_2->setPlainText(string);
    }

    if(Line == 4)
    {
        ui->printerArea->setPlainText(string);
    }
}

You can not use a C++ method directly, you have to create a function in order to call your object's method. 你不能直接使用C ++方法,你必须创建一个函数来调用你的对象的方法。 Here is an example (part of a C++ file): 这是一个例子(C ++文件的一部分):

extern C 
{

    void   example(int Line, char *string)
    {
       static MainWindow win;

       win.putsDisplay(Line, string); 
    }

}

C code: C代码:

int main()
{
    example(42, "it is an example");
    return 0;
}

extern C will disabled name mangling, so example() can be called from C code. extern C将禁用名称修改,因此可以从C代码调用example() You can keep static MainWindow win; 你可以保持static MainWindow win; , or made it global or whatever, but you will need an MainWindow object. ,或使它成为全局或其他,但你需要一个MainWindow对象。

Remember, C is a subset of C++. 请记住,C是C ++的子集。

You can name the file that has the C code as xC or x.cpp and compile it with the rest of the files with c++ compiler. 您可以将具有C代码的文件命名为xC或x.cpp,并使用c ++编译器将其与其余文件一起编译。 Then you will be able to call the C++ method from the C code. 然后,您将能够从C代码中调用C ++方法。

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

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