c++ - 使用字符串参数创建 SDL_thread

标签 c++ multithreading sdl

我正在尝试制作一个以字符串作为输入的多线程程序。使用 SDL_CreateThread,我尝试构建一个像这样的简单实现:

#include <stdio.h>
#include <string>
#include <SDL_thread.h>

int threadFunction(void* data) {
    std::string* parameter = static_cast<std::string *>(data);
    printf("Thread data: %s\n", parameter);
    return 0;
}

int main(int argc, char const *argv[]) {
    SDL_Thread* threadID = SDL_CreateThread(threadFunction, "test", (void*)"Enter string here");
    SDL_DetachThread(threadID);
    return 0;
}

它工作得很好,但每当我将一个整数放入字符串中(例如 "123",而不是直接输入数字 123),然后尝试解析该整数在线程中,我得到一个 Segmentation Fault: 11。我的尝试是 int i = std::stoi(parameter->c_str());

谁能解释一下为什么?是否与从 void* 进行转换有关?

最佳答案

好的,您首先传递一个指向 char 数组的指针 (void*)"Enter string here"作为线程参数然后将此指针转换为指向字符串 static_cast<std::string *>(data) 的指针.::std::string 是一个类,在任何情况下都不能接受执行此类转换。当 printf("Thread data: %s\n", parameter) 时,您还隐式地将指向字符串的指针转换为指向字符数组的指针。但这不会引爆错误,因为它确实指向 char 数组,而不是字符串。

int threadFunction(void* data) {
const char * parameter = static_cast< const char * >(data); // correct cast

关于c++ - 使用字符串参数创建 SDL_thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43463337/

相关文章:

Java在线程中更改字符串值

android - SDL 下 Android OpenGL ES 渲染中不确定的不需要的额外三角形

python - SDL/Pygame 无法使用 cx_Freeze 加载 PNG 图像

c++ - C/C++ 中的指针编译但给出段错误

python - 在许多单独的线程中测试 Django 应用程序

python - (Python) 在线程中关闭 pygame.display

OpenGL 旋转对象,同时将其保持在屏幕中心

c++ - 在这种情况下要考虑的有效 C++ 数据结构

填充 vector 的 C++ 有状态仿函数

c++ - Delphi 库内存管理器奇怪