简体   繁体   中英

C++ Converting a char to a const char *

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 *.

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);

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());

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM