无法用多文件程序创建SDL线程

Unable to create SDL thread with multi file program

本文关键字:创建 SDL 线程 程序 文件      更新时间:2023-10-16

我有一个问题与SDL线程所以我做了一个小的多文件代码,这样它将更容易显示我的问题

头文件

#ifndef MAINC_H_INCLUDED
#define MAINC_H_INCLUDED
#include <iostream>
#include <CONIO.H>
#include <SDL.h>
#include <SDL_thread.h>
using namespace std;
class mainc
{
    private:
        SDL_Thread* thread;
        int threadR;
        int testN=10;
    public:
        int threadF(void *ptr);
        int OnExecute();
        bool start();
};
#endif

一个文件

#include "mainc.h"
bool mainc::start() {
if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
    return false;
}
getch();
if(SDL_CreateThread(threadF, "TestThread", (void *)NULL)==NULL){
return false;
}
return true;
}
int mainc::threadF(void *ptr){
cout<<"This is a thread and here is a number: "<<testN<<endl;
return testN;
}
第二文件

#include "mainc.h"
int mainc::OnExecute() {
    if(!start())
    {
        return -1;
    }
    SDL_WaitThread(thread,&threadR);
    return 0;
}
int main(int argc, char* argv[]) {
    mainc game;
    return game.OnExecute();
}

当我编译这个时,我得到这个错误

cannot convert 'mainc::threadF' from type 'int (mainc::)(void*)' to type 'SDL_ThreadFunction {aka int (*)(void*)}'

我挖了一下,找到了一个解决方案,但它给了我其他错误我需要使threadF静态,但我不能访问任何变量它给了我这个错误

invalid use of member 'mainc::testN' in static member function

但是如果我从函数中删除变量,它运行良好现在我不知道该怎么做了因为在我的游戏中我需要共享变量

testN既不是类mainc的静态属性也不是公共属性,要做您想做的事情,它需要两者之一。如果你想在另一个线程体中使用"mainc"类的成员,你需要传递一个指向"mainc"类对象的指针给SDL_CreateThread:

// ...
SDL_CreateThread(threadF, "TestThread", this)
// ...

然后

int mainc::threadF(void *ptr)
{
   mainc* myMainc = (mainc*)ptr;
   myMainc->testN; // now you can use it as you need
}

注意封装,但是(testN实际上是私有的)