【问题标题】:SDL2 Thread not working inside classSDL2 线程在类内不起作用
【发布时间】:2017-04-17 17:57:36
【问题描述】:

我正在尝试使用 SDL2 库的多线程创建输入处理程序;但是,当我尝试将线程放在一个类中时,它不会编译并给我这个错误......

error: cannot convert 'inputHandlerClass::getInput' from type 'int (inputHandlerClass::)(void*)' to type 'SDL_ThreadFunction {aka int (*)(void*)}'

我很确定这是我将函数名称 (fn) 传递给 SDL_CreateThread 函数的方式。

这是source.cpp文件

#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_thread.h>
#include <SDL_mixer.h>
#include "..\include\gameClass.hpp"
#include "..\include\inputHandlerClass.hpp"

int main(int argc, char *argv[]){
    inputHandlerClass inputHandler;
    inputHandler.startThread();
    std::cout << "hello world";
    return 0;
}

这是 inputHandlerClass.hpp

#include <SDL_thread.h>
#include <iostream>

class inputHandlerClass{
    private:
        SDL_Thread *thread;
        int threadReturnValue;
    public:
        inputHandlerClass();
        int getInput(void *ptr);
        void startThread();
};

//Default Constructor
inputHandlerClass::inputHandlerClass(){
    this->thread = SDL_CreateThread(getInput, "inputThread", this);
}

int inputHandlerClass::getInput(void *ptr){
    int cnt;
    for(cnt= 0; cnt < 10; ++cnt){
        std::cout << "counter: " << cnt << std::endl;
        SDL_Delay(50);
    }
    return cnt;
}

void inputHandlerClass::startThread(){
    SDL_WaitThread(this->thread, &this->threadReturnValue);
}

【问题讨论】:

    标签: c++ multithreading class pointers sdl-2


    【解决方案1】:

    SDL_CreateThread 需要一个指向带有int(void *ptr) 签名作为第一个参数的常规函数​​的指针,但是您提供的是非静态成员函数(甚至不是指针,因为成员函数没有被隐式转换为指针) .您应该将getInput 重新声明为静态。 this 指针将以ptr 的形式提供。

    【讨论】:

    • 我尝试重新声明为静态成员函数,但现在出现以下错误。错误:不能声明成员函数'static int inputHandlerClass::getInput(void*)'具有静态链接[-fpermissive]
    • 也许你改变了函数定义而不是声明?
    • 我找到了解决办法。我正在使用 gnu 编译器,当我给编译器 -fpermissive 标志时,它忽略了错误,并成功编译。
    • 你应该修复错误而不是使用-fpermissive。通常代码编译时应使用-Wall -Wextra -Wconversion -pedantic 不带任何警告,而严禁使用-fpermissive
    • 你说得对,不依赖临时修复,但现在我让它在没有警告的情况下工作。我只需要从定义中取出静态,但将它留在类声明中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多