C++ void*到C+中的数组+;对于线程
我使用的是线程库(没什么特别的) 可以在线程函数中将void*强制转换为字符串数组吗C++ void*到C+中的数组+;对于线程,c++,multithreading,casting,C++,Multithreading,Casting,我使用的是线程库(没什么特别的) 可以在线程函数中将void*强制转换为字符串数组吗 #define THREAD_IMPLEMENTATION #include "thread.h" #include <stdio.h> // for printf int thread_proc( void* user_data) { //Cast user_data to string array here return 0; } int main( int argc
#define THREAD_IMPLEMENTATION
#include "thread.h"
#include <stdio.h> // for printf
int thread_proc( void* user_data)
{
//Cast user_data to string array here
return 0;
}
int main( int argc, char** argv )
{
std::string foo[1] = {"Hello from array"};
thread_ptr_t thread = thread_create( thread_proc, &foo, "Example thread", THREAD_STACK_SIZE_DEFAULT );
return 0;
}
#定义线程#实现
#包括“thread.h”
#包括//用于printf
int线程进程(无效*用户数据)
{
//在此处将用户\u数据强制转换为字符串数组
返回0;
}
int main(int argc,字符**argv)
{
std::string foo[1]={“Hello from array”};
thread_ptr_t thread=thread_create(thread_proc,&foo,“示例线程”,thread_STACK_SIZE_DEFAULT);
返回0;
}
您需要记住三件事:
&foo
的类型是std::string(*)[1]
foo
,那么它将被翻译成&foo[0]
,并且类型为std::string*
对于一个特定于C++的解决方案,它可以看起来像这样
#include <array>
#include <string>
#include <thread>
#include <functional> // For std::cref, see https://en.cppreference.com/w/cpp/utility/functional/ref
void thread_proc(std::array<std::string, 1> const& strings)
{
// Use the (constant) array as you please here...
}
int main()
{
std::array<std::string, 1> foo = { "Hello from array" };
std::thread thread(&thread_proc, std::cref(foo));
// Do things here...
thread.join();
}
#包括
#包括
#包括
#include//对于std::cref,请参见https://en.cppreference.com/w/cpp/utility/functional/ref
无效线程进程(标准::数组常量和字符串)
{
//请在此处随意使用(常量)数组。。。
}
int main()
{
std::array foo={“Hello from array”};
std::thread thread(&thread_proc,std::cref(foo));
//在这里做事。。。
thread.join();
}
不需要铸造。唯一的问题是,在创建线程对象时,需要使用std::ref
或std::cref
传递引用(因为需要复制参数,而无法复制引用)
可以在线程函数中将void*强制转换为字符串数组吗
#define THREAD_IMPLEMENTATION
#include "thread.h"
#include <stdio.h> // for printf
int thread_proc( void* user_data)
{
//Cast user_data to string array here
return 0;
}
int main( int argc, char** argv )
{
std::string foo[1] = {"Hello from array"};
thread_ptr_t thread = thread_create( thread_proc, &foo, "Example thread", THREAD_STACK_SIZE_DEFAULT );
return 0;
}
这是不可能的。但是你可以将void*
转换为指向任何对象的指针,只要该指针指向该类型的对象
在本例中,您已经初始化了void指针,指向std::string foo[1]
。因此,您可以将其转换回:
auto ptr_to_foo = static_cast<std::string (*)[1]>(user_data); // same as &foo
auto ptr_to_foo=static_cast(用户数据);//与&foo相同
然后,您可以间接调用指针:
auto& foo_ref = *ptr_to_foo;
std::cout << foo_ref[0];
auto&foo\u ref=*ptr\u to\u foo;
std::cout@Quentin-Nah,只是“幸运”:)谢谢你@Someprogrammerdude。我一定要用std::thread。谢谢。这很有教育意义