无法将字符串传递给CreateThread接收器 [英] Cannot pass string to CreateThread receiver

查看:226
本文介绍了无法将字符串传递给CreateThread接收器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程函数,看起来像这样:

I have a thread function that looks something like this:

DWORD WINAPI Thread_ProcessFile( LPVOID lpParam )  {
 char *filename = (char*)lpParam;
 printf( "%s\n", filename );
}



我还有一个类调用CreateThread并使用上述函数地址:

I also have a class that calls CreateThread and uses the above function for the routine address:

void CMyClass::ProcessFile( void ) {
 HANDLE tHwnd = 0;
 char szBuffer[128];
 strcpy( szBuffer, "test_string" );

 tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)szBuffer, 0, NULL );  
 if ( tHwnd == NULL )
  return;
}

问题是程序正在接收/打印垃圾字符串,而不是真实的东西(例如,随机字符集,如果有的话)。如果我这样做:

The problem is that the routine is receiving/printing a garbage string and not the real thing (eg. random set of characters, if any). If I do this, however:

tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)"test_string", 0, NULL );

接收并正确打印字符串。如何正确构建一个字符串并将其传递给我的线程函数?

the string is received and printed correctly. How can I properly build a string and pass it to my thread function?

推荐答案

您正在堆栈上创建szBuffer。因此,在你的线程启动的时候,ProcessFile()函数将返回,堆栈变量将被释放。因此,你得到的垃圾值。在第二种情况下,你传递一个const字符串,其中post可能驻留在进程内存的只读部分,并且不会释放在函数return(我不认为这是保证的行为,我不会依靠它)。所以你在函数中获得了正确的价值。你可以使用new []在堆上分配字符串,并将指针传递给线程。不要忘记在线程中完成处理后删除[]。

You are creating the szBuffer on the stack. Hence by the time your thread starts, the ProcessFile() function would have returned and the stack variable would have been deallocated. Hence you are getting the garbage value. In the second case, you are passing a const-string which post probably resides in the read-only part of the process memory and is not deallocated on the function return (I don't think this is the guaranteed behavior, I wouldn't rely on it). So you are getting proper value in the function. You can allocate the string on the heap using new[] and pass the pointer to the thread. Don't forget to to delete[] once the processing is completed in the thread.

这篇关于无法将字符串传递给CreateThread接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆