I'm trying to use beginthreadex to create a thread that will run a function that takes a char as an argument. I'm bad at C++, though, and I can't figure out how to turn a char into a const char , which beginthreadex needs for its argument. Is there a way to do that? I find a lot of questions for converting a char to a const char, but not to a const char *.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
回答2:
If the function expects a const pointer to an exiting character you should go with the answer of Paul Draper. But keep in mind that this is not a pointer to a null terminated string, what the function might expect. If you need a pointer to 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());
回答3:
Since you didn't show any code it's hard to know exactly what you want, but here is a way to call a function expecting a char as an argument in a thread. If you can't change the function to convert the argument itself you need a trampoline function to sit in the middle to do that 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;
}