SFML community forums

Help => System => Topic started by: Trampampam on November 11, 2012, 11:43:11 am

Title: Smth wrong with getting parameter in function for sf::Thread
Post by: Trampampam on November 11, 2012, 11:43:11 am
I'm trying to get char * made in such way:
#include <string>
#include <cstring>
...
void smthInThread(void *UserData){
//some everlasting loop from which the thread "threadEval" will call
while(true){
  //getting std::string str from console
  std::string str;
  std::getline(std::cin, str);

  //getting cstring cstr from str
  char * cstr;
  cstr = new char [str.size()+1];
  strcpy(cstr,str.c_str());

  //passing cstr into evalInThread where problem is
  sf::Thread threadEval(&evalInThread, &cstr);
  threadEval.Launch();
}
}

//!function where problem is:
void evalInThread(void *UserData){
  //That's in tutorial:
  // Cast the parameter back to its real type
  //  MyClass* Object = static_cast<MyClass*>(UserData);

  //That's what I'm doing:
  char * evalString = static_cast<char *>(UserData);
  std::cout << evalString; //!! This return wrong string !!
}
 

The problem is that I can not cast the parameter of char * back to its real type, although I do all as in tutorial written
What I'm doing wrong?
Or, maybe, there's another way to get parameter of such type inside threaded function?

btw: I am using SFML ver 1.6 'cause I need stable version
Title: Re: Smth wrong with getting parameter in function for sf::Thread
Post by: Nexus on November 11, 2012, 11:47:46 am
If you already include the <string> header, why don't you consequently use the std::string class? It is much more comfortable and safer than raw char* strings. And your memory leak would not exist, either.

Your other problem is that you have one indirection too much, you take the address of the pointer. But seriously, just pass str.c_str(), which gives you a const char* out of a std::string.