gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:45:33 26 4
gpt4 key购买 nike

我正在尝试制作一个以字符串作为输入的多线程程序。使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com