I would like to convert a CLSID to a *char in c++ so I can display it in a text box. I am new to c++ so please make this as simple a s possible.
Thanks
C'ish solution:
/* 128 bit GUID to human-readable string */
char * guid_to_str(const GUID * id, char * out) {
int i;
char * ret = out;
out += sprintf(out, "%.8lX-%.4hX-%.4hX-", id->Data1, id->Data2, id->Data3);
for (i = 0; i < sizeof(id->Data4); ++i) {
out += sprintf(out, "%.2hhX", id->Data4[i]);
if (i == 1) *(out++) = '-';
}
return ret;
}
This assumes the output buffer has been already allocated, and should be of a size of 37 bytes (including the null terminating character).
The output is of the form "75B22630-668E-11CF-A6D9-00AA0062CE6C"
Usage example:
GUID g;
char buffer[37];
std::cout << guid_to_str(&g, buffer);
Note:
This code exists because I had to implement GUID parsing under Linux, otherwise I would have used the Windows API function StringFromCLSID mentioned by #krowe.
Here is a great example for converting GUID to string and vice versa that I am using in my projects:
std::string guidToString(GUID guid) {
std::array<char,40> output;
snprintf(output.data(), output.size(), "{%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::string(output.data());
}
GUID stringToGUID(const std::string& guid) {
GUID output;
const auto ret = sscanf(guid.c_str(), "{%8X-%4hX-%4hX-%2hX%2hX-%2hX%2hX%2hX%2hX%2hX%2hX}", &output.Data1, &output.Data2, &output.Data3, &output.Data4[0], &output.Data4[1], &output.Data4[2], &output.Data4[3], &output.Data4[4], &output.Data4[5], &output.Data4[6], &output.Data4[7]);
if (ret != 11)
throw std::logic_error("Unvalid GUID, format should be {00000000-0000-0000-0000-000000000000}");
return output;
}
In the example, it firsts uses char* before converting to string so this is exactly what you are looking for in an efficient way.
The Windows API has a function for this:
CLSID clsid;
HRESULT hr = CLSIDFromProgID ((OLESTR "Adobe.SVGCtl.3"),&clsid);
// Get class id as string
LPOLESTR className;
hr = StringFromCLSID(clsid, &className);
// convert to CString
CString c = (char *) (_bstr_t) className;
// then release the memory used by the class name
CoTaskMemFree(className);
// Now c is ready to use
A CLSID is the same as a UUID, so you can use the UuidToString() function
http://msdn.microsoft.com/en-us/library/windows/desktop/aa379352(v=vs.85).aspx
Related
C# code:
class Hello{
public void helloWorld(char[] chars){
//do something
}
}
C++ code to call C#:
MyCSDLL::Hello* hello;
//init hello, some calls are ok.
char* myCharPtr;
//init with message
HRESULT result = hello->helloWorld(safeArray, (MyCSDLL::_MyRetVal) _retValPtr);
Adapting from How to create and initialize SAFEARRAY of doubles in C++ to pass to C#
void createSafeArray(SAFEARRAY** saData, char* charPtr)
{
char* iterator = charPtr;
SAFEARRAYBOUND Bound;
Bound.lLbound = 0;
Bound.cElements = 10;
*saData = SafeArrayCreate(VT_R8, 1, &Bound);
char HUGEP *pdFreq;
HRESULT hr = SafeArrayAccessData(*saData, (void HUGEP* FAR*)&pdFreq);
if (SUCCEEDED(hr))
{
do {
*pdFreq++ = *iterator;
} while (*iterator++);
}
}
How to call hello->helloWorld()? it is expecting SAFEARRAY*. The current code gives 80131538 error. How to fix it?
C++ Project is not CLR.
Let's suppose the C# code is this:
namespace ClassLibrary1
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Hello
{
public void helloWorld(char[] chars)
{
...
}
}
}
Then, you can call it with this C/C++ code, for example:
#import "C:\mycode\ClassLibrary1\bin\Debug\classlibrary1.tlb" raw_interfaces_only
using namespace ClassLibrary1;
HRESULT CallHello(wchar_t* charPtr, int count)
{
CComPtr<_Hello> p;
HRESULT hr = p.CoCreateInstance(__uuidof(Hello));
if (FAILED(hr))
return hr;
SAFEARRAY* psa = SafeArrayCreateVector(VT_UI2, 0, count);
if (!psa)
return E_OUTOFMEMORY;
LPVOID pdata;
hr = SafeArrayAccessData(psa, &pdata);
if (SUCCEEDED(hr))
{
CopyMemory(pdata, charPtr, count * 2); // count is the number of chars
SafeArrayUnaccessData(psa);
hr = p->helloWorld(psa);
}
SafeArrayDestroy(psa);
return hr;
}
.NET's char type is unicode, so the binary size is two bytes, the C equivalent is wchar_t (or unsigned short, etc...). So the safearray element type must match that, that's why I used VT_UI2 (VT_R8 that you used is Real of size 8 bytes, so it's equivalent to .NET's double type).
If you really want to use C's char, then you must do some kind of conversion to a 2-byte character.
Also, you can use the SafeArrayCreateVector function which directly allocates a 1-dimension safe array. Don't forget to call cleanup methods.
I'm actually working lkm on linux 2.6.32, and I don't to understand one thing. I'm trying to change the original read_proc and write_proc of /proc/version with my functions. Thus I can to change the original value of read_proc and write_proc, with values of my function. I can see it, because values of read_proc and write_proc change to NULL to adress of my functions, but that have no effect... And I don't understand why. I don't arrive to find if version is protected (I tried to change the value of file's right with chmod), or why even after change the value, I can't write in /proc/version with echo XXXX > /proc/version. I'll be grateful for your help.
Code where I try to change values of read_proc and write_proc:
static void Proc_init()
{
int find = 0;
pde = create_proc_entry("test", 0444, NULL); //that permit to create new file in /proc, only to get some useful values
ptdir = pde->parent; //affect to ptdir the value of the pointer on /proc
if(strcmp(ptdir->name, "/proc")!=0)
{
Erreur=1;
}
else
{
root = ptdir;
remove_proc_entry("test", NULL);
ptr_subdir=root->subdir;
while(find==0)
{
printk("%s \n", ptr_subdir->name);
if(strcmp("version", ptr_subdir->name)==0)
find=1;
else
ptr_subdir=ptr_subdir->next;
}
//Save original write et read proc
old_read_proc=ptr_subdir->read_proc;
old_write_proc=ptr_subdir->write_proc;
// Before I have null values for prt_subdir->read_proc and ptr_subdir->write_proc
ptr_subdir->read_proc=&new_read_proc_t;
ptr_subdir->write_proc=&new_write_proc_t;
// after that, values of prt_subdir->read_proc and ptr_subdir- >write_proc are egual to values of &new_write_proc_t and &new_read_proc_t
}
}
static int new_read_proc_t (char *page, char **start, off_t off,int count, int *eof, void *data)
{
int len;
/* For example - when content of our_buf is "hello" - when user executes command "cat /proc/test_proc"
he will see content of our_buf(in our example "hello" */
len = snprintf(page, count, "%s", our_buf);
return len;
}
static int new_write_proc_t(struct file *file, const char __user *buf,unsigned long count, void *data)
{
/* If count is bigger than 255, data which user wants to write is too big to fit in our_buf. We don't want
any buffer overflows, so we read only 255 bytes */
if(count > 255)
count = 255;
/* Here we read from buf to our_buf */
copy_from_user(our_buf, buf, count);
/* we write NULL to end the string */
our_buf[count] = '\0';
return count;
}
As part of a WinRT C++cx component, what's the most efficient way to convert an unmanaged buffer of bytes (say expressed as a std::string) back and forth with a Windows::Web::Http::HttpBufferContent?
This is what I ended up with, but it doesn't seem very optimal:
std::string to HttpBufferContent:
std::string m_body = ...;
auto writer = ref new DataWriter();
writer->WriteBytes(ArrayReference<unsigned char>(reinterpret_cast<unsigned char*>(const_cast<char*>(m_body.data())), m_body.length()));
auto content = ref new HttpBufferContent(writer->DetachBuffer());
HttpBufferContent to std::string:
HttpBufferContent^ content = ...
auto operation = content->ReadAsBufferAsync();
auto task = create_task(operation);
if (task.wait() == task_status::completed) {
auto buffer = task.get();
size_t length = buffer->Length;
if (length > 0) {
unsigned char* storage = static_cast<unsigned char*>(malloc(length));
DataReader::FromBuffer(buffer)->ReadBytes(ArrayReference<unsigned char>(storage, length));
auto m_body = std::string(reinterpret_cast<char*>(storage), length);
free(storage);
}
} else {
abort();
}
UPDATE: Here's the version I ended up using (you can trivially create a HttpBufferContent^ from an Windows::Storage::Streams::IBuffer^):
void IBufferToString(IBuffer^ buffer, std::string& string) {
Array<unsigned char>^ array = nullptr;
CryptographicBuffer::CopyToByteArray(buffer, &array); // TODO: Avoid copy
string.assign(reinterpret_cast<char*>(array->Data), array->Length);
}
IBuffer^ StringToIBuffer(const std::string& string) {
auto array = ArrayReference<unsigned char>(reinterpret_cast<unsigned char*>(const_cast<char*>(string.data())), string.length());
return CryptographicBuffer::CreateFromByteArray(array);
}
I think you are making at least one unnecessary copy of your data in your current approach for HttpBufferContent to std::string, you could improve this by accessing the IBuffer data directly, see the accepted answer here: Getting an array of bytes out of Windows::Storage::Streams::IBuffer
I think it's better to use smart pointer (no memory management needed) :
#include <wrl.h>
#include <robuffer.h>
#include <memory>
using namespace Windows::Storage::Streams;
using namespace Microsoft::WRL;
IBuffer^ buffer;
ComPtr<IBufferByteAccess> byte_access;
reinterpret_cast<IInspectable*>(buffer)->QueryInterface(IID_PPV_ARGS(&byte_access));
std::unique_ptr<byte[]> raw_buffer = std::make_unique<byte[]>(buffer->Length);
byte_access->Buffer(raw_buffer.get());
std::string str(reinterpret_cast<char*>(raw_buffer.get())); // just 1 copy
I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.
This is a code that does not work (string argument 2 expected!)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
I don't exactly know what language is that (C++?), but you seem to be passing a char to strcat() instead of a null-terminated string. It's a subtle difference, but strcat will happily access further invalid memory positions until a null byte is found.
Instead of using strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.
Here's my implementation in C:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
I made it return an empty string for the case that repeat == 0 because that's how it works in PHP, according to the online manual.
This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
This prints:
Hello, world!!!!!!!
Convert char to string.
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}
I want to display all ascii characters(http://msdn.microsoft.com/en-us/library/Aa245273) including NULL in richEdit2 control of visual c++ but i don't know how?
so please help help me how can i do this?
Actually i can show all character but when ASCII NUL is found from that richedit box doesn't show any further character and i want to display all character my code is given below please help me
my code is given below
void CclientCheckDlg::ReadFileData()
{
char *readfilename= configfilepath ;
//FILE *fp=fopen(readfilename ,"r");
std::ifstream openFile(readfilename,std::ios::out | std::ios::binary);
//string s;
unsigned char c;
//std::string s;
int i=0;
do
{
c=openFile.get();
if(c==EOF||i==999)
break;
unsignedCharPointer[i]=c;
i++;
printf("%c",c);
}while(!openFile.eof());
//fclose(fp);
CString cs(unsignedCharPointer);
OutputDebugString(cs);
// configArrStr=s.c_str();
int begin=m_rich_edit.GetTextLength();
m_rich_edit.SetSel(begin,begin);
// CA2CT ct(unsignedCharPointer);
lpctstr=(LPCTSTR)unsignedCharPointer;
OutputDebugString(lpctstr);
m_rich_edit.ReplaceSel(cs);
}
so please can anyone help me,how can i display null character?
//function to read binary file(Unicode) and write to richedit2
void function()
{
CFile cFile(TEXT("edit.moc"), CFile::modeRead);
EDITSTREAM es={0};
//HWND hwnd=getwin
OutputDebugStringA("........... OnBnClickedButton1() ");
es.pfnCallback= &EditStreamCallBack;
es.dwCookie = (DWORD) &cFile;
m_richEdit.StreamIn(SF_TEXT, es);
LRESULT result = SendMessageA(::GetDlgItem(hwnd, IDC_RICHEDIT21),EM_STREAMIN,SF_TEXT,(LPARAM)&es);
}
//callback function, declared in header file
DWORD CALLBACK EditStreamCallBack(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
//MessageBoxA(L"hi...1");
OutputDebugStringA("........... OnBnClickedButton1() 2");
CFile* pFile = (CFile*) dwCookie;
*pcb = pFile->Read(pbBuff, cb);
return 0;
}
Thank you all.