C++ 将字符转换为常量字符 *
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20561277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Converting a char to a const char *
提问by user3098417
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 *.
我正在尝试使用 beginthreadex 创建一个线程,该线程将运行一个将 char 作为参数的函数。不过,我不擅长 C++,而且我不知道如何将 char 转换为 const char ,而 beginthreadex 需要它作为参数。有没有办法做到这一点?我发现很多关于将 char 转换为 const char而不是 const char * 的问题。
回答by Paul Draper
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);
回答by hansmaad
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
如果该函数需要一个指向退出字符的 const 指针,您应该使用 Paul Draper 的答案。但请记住,这不是函数可能期望的指向空终止字符串的指针。如果你需要一个指向空终止字符串的指针,你可以使用std::string::c_str
f(const char* s);
char a = 'z';
std::string str{a};
f(str.c_str());
回答by Retired Ninja
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.
由于您没有显示任何代码,因此很难确切地知道您想要什么,但这里有一种方法可以调用期望 char 作为线程中参数的函数。如果您无法更改函数以转换参数本身,则需要一个蹦床函数来执行此操作并调用实际函数。
#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;
}