如何在 C++ 中将对象传递给 TThread 函数?

问题描述 投票:0回答:1

如何将对象传递给 TThread 函数?这是基于我找到的示例的代码。它编译并成功运行,直到我添加 Synchronize(OutputString...)。

我正在从 Form1 中的 TEdit 输入一个字符串,并尝试将其输出到 Form1 中的另一个 TEdit。错误消息是“[bcc32c Error] Unit2.cpp(60): nomatching member function for call to 'Synchronize'”。

这是 TThread 代码:

//---------------------------------------------------------------------------

#include <System.hpp>
#pragma hdrstop

#include "Unit2.h"
#include "Unit1.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(&UpdateCaption);
//
//   where UpdateCaption could look like:
//
    void __fastcall TSortThread::UpdateCaption()
    {
        Form1->Button1->Caption = "Done!";
    }

    void __fastcall TSortThread::OutputString(wchar_t *string)
    {
        Form1->Edit2->Text = string;
    }
//---------------------------------------------------------------------------

__fastcall TSortThread::TSortThread(bool CreateSuspended)
    : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall TSortThread::Execute()
{
    NameThreadForDebugging(System::String(L"SortingThread"));
    //---- Place thread code here ----

    FreeOnTerminate = true;

    for(int i=0;i<50000 - 1;++i)  {

        for(int j=0;j<50000 - 1 - i;++j)  {

            if(Form1->dataField[j] > Form1->dataField[j+1]) {

                int temp = Form1->dataField[j];
                Form1->dataField[j] = Form1->dataField[j+1];
                Form1->dataField[j+1] = temp;
            }
        }
    }

    Synchronize(UpdateCaption);

    // input and output string
    wchar_t inputString[100];
    wcscpy(inputString,Form1->Edit1->Text.c_str());

    Synchronize(OutputString(inputString)); // COMPILE ERROR
}
//---------------------------------------------------------------------------

这是头文件:

//---------------------------------------------------------------------------

#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
//---------------------------------------------------------------------------
class TSortThread : public TThread
{
protected:
    void __fastcall Execute();
public:
    __fastcall TSortThread(bool CreateSuspended);
    void __fastcall UpdateCaption();
  void __fastcall OutputString(wchar_t *string);
};
//---------------------------------------------------------------------------
#endif
c++ c++builder tthread
1个回答
0
投票

// 重要提示:VCL 中对象的方法和属性只能是
// 在调用 Synchronize 的方法中使用

但是您正在“不同步执行”中访问“VCL 中对象的属性”。我的意思是 Form1 对象及其属性。

2.

关于你的问题。您可以在 TSortThread 类中创建 wchar_t[] 类型(或其他类型)的成员变量。在调用 Synchronize(OutputString) 之前为其分配所需的值。 IE。通过成员变量而不是方法参数传递值,并在 OutputString 中使用它

© www.soinside.com 2019 - 2024. All rights reserved.