ヘッダー ファイル:
// Free function to use in thread
unsigned int __stdcall WorkerFunction(void *);
class MyClass {
public:
int temp;
void StartThread();
}
typedef struct {
MyClass * cls;
} DATA;
CPP クラス:
void MyClass::StartThread() {
temp = 1234;
DATA data = {this};
HANDLE hThread = (HANDLE) _beginthreadex(0, 0, &WorkerFunction, &data, 0, 0);
// Commented out for now while I address the current problem
//CloseHandle(hThread);
}
unsigned int __stdcall WorkerFunction(void * param0) {
MessageBox(NULL, "WorkerFunction()", "Alert", MB_OK);
DATA * data = (DATA *) param0;
MyClass* cls0 = data->cls;
// Crashes when reference to cls0 is attempted.
char buf[5];
snprintf(buf, 5, "%i", cls0 ->temp);
MessageBox(NULL, buf, "Alert", MB_OK);
}
ここには、指を置くことができない簡単な問題があります。
- クラスを含む構造体を渡すスレッドのパラメーターがあります。
- 構造体をインスタンス化し
this
、スレッドの開始時に渡します - ワーカー関数で逆参照 (?) しようとしています。
- この時点で、すべてが正常にコンパイルされます。
- クラス内の何かにアクセスする行を追加すると、アプリがクラッシュします。
私の間違いはどこですか?