C ++ Convert a char to const char *

I am trying to use beginthreadex to create a thread that will run a function that takes a char argument. I am not good at C ++, but I cannot figure out how to turn char into const char, which beginthreadex needs its argument. Is there any way to do this? I find many questions for converting char to const char, but not to const char *.

+6
source share
3 answers
char a = 'z'; const char *b = &a; 

Of course, this is on the stack. If you need it on the heap,

 char a = 'z'; const char *b = new char(a); 
+9
source

If the function expects a const pointer at the character's output, you should go with Paul Draper's answer. But keep in mind that this is not a pointer to a null-terminated string, which a function might expect. If you need a pointer to a null-terminated string, you can use std::string::c_str

 f(const char* s); char a = 'z'; std::string str{a}; f(str.c_str()); 
0
source

Since you have not shown any code, it is difficult for you to know exactly what you want, but here is a way to call a function that expects char as an argument in the stream. If you cannot change the function to convert the argument itself, you will need a trampoline function to sit in the middle to do this and call the actual function.

 #include <Windows.h> #include <process.h> #include <iostream> void ActualThreadFunc(char c) { std::cout << "ActualThreadFunc got " << c << " as an argument\n"; } unsigned int __stdcall TrampolineFunc(void* args) { char c = *reinterpret_cast<char*>(args); std::cout << "Calling ActualThreadFunc(" << c << ")\n"; ActualThreadFunc(c); _endthreadex(0); return 0; } int main() { char c = '?'; unsigned int threadID = 0; std::cout << "Creating Suspended Thread...\n"; HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &TrampolineFunc, &c, CREATE_SUSPENDED, &threadID); std::cout << "Starting Thread and Waiting...\n"; ResumeThread(hThread); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); std::cout << "Thread Exited...\n"; return 0; } 
0
source

All Articles