Corne Corne - 1 year ago 178
C++ Question

converting void* pointing to char* to a std::string in c++

From the wincrypt api I am receiving a void* pointing to a char*.
This char* is a char[]. I am also receiving a

pointing to a int with the size of the

Regarding pvData and cbData I have the following documentation from Microsoft.

Data type of pvData: A pointer to an array of BYTE values. The size of this array is specified in the cbData parameter. Returns a null-terminated Unicode character string that contains the display name for the certificate.

I want to convert this
to a
but so far all I am getting when outputting my
is the first character.

I have read: Converting a void* to a std::string but since my
is pointing to a
instead of
in the accepted answer fails and the returned
triggers a null pointer exception.

So far I have the following:

// pvData = void* pointing to char*
// cbData = void* pointing to int*
std::string tempName;
tempName.assign(static_cast<char*>(pvData), static_cast<int*>(cbData));
printf("%S \n", pvData); // entire string is shown
printf("%s \n", tempName.c_str()); // only first character is shown

I have also tried

tempName = static_cast<char*>(pvData); // only single character returned

tempName.assign(static_cast<char*>(pvData)); // only single character returned

char* arr = static_cast<char*>(pvData);
std::string tempName(arr); // only single character returned empty with printf must
// use std::cout

qxz qxz
Answer Source

If the char buffer isn't null-terminated, then to use the (void*)cbData length:

char* data = static_cast<char*>(pvData);
size_t len = *static_cast<int*>(cbData);
std::string tempName(data, len);

See the std::string constructor reference (#5, from buffer) and ::assign reference (#4, buffer).

EDIT: If you're trying to use the function CertGetCertificateContextProperty with dwPropId CERT_FRIENDLY_NAME_PROP_ID, here is how you should call the function:

BYTE buf[100];
DWORD len = 100;
CertGetCertificateContextProperty(&ctx, CERT_FRIENDLY_NAME_PROP_ID, buf, &len);
std::string tempName(reinterpret_cast<char*>(buf), len);

No dealing with void* pointers!