I am curious why Alternative #1 functions okay while Alternative #2 returns CURLE_OPT_MALFORMAT when I do a curl_easy_perform(m_curl);
Alternative #1 curl_easy_reset(m_curl); char sUrl[8192]; /* In Alternative #1, m_strUrl is a C++ std::wstring member variable */ wcstombs(sUrl, m_sUrl.c_str(), m_sUrl.length()); sUrl[m_sUrl.length()] = '\0'; CURLcode code = curl_easy_setopt(m_curl, CURLOPT_URL, sUrl); CURLcode perform = curl_easy_perform(m_curl);
Alternative #2 curl_global_init(CURL_GLOBAL_ALL); /* init the curl session / m_curl_handle = curl_easy_init(); / set URL to get here*/ /* In Alternative #2, m_strUrl is a C++ std::string member variable */ CURLcode retval = curl_easy_setopt(m_curl_handle, CURLOPT_URL, (char *)m_sUrl.c_str()); CURLcode perform = curl_easy_perform(m_curl);
I read the following URL
How to convert a std::string to const char* or char*?
If you just want to pass a std::string to a function that needs const char* you can use std::string str; const char * c = str.c_str(); If you want to get a writable copy, like char *, you can do that with this: std::string str; char * writable = new char[str.size() + 1]; std::copy(str.begin(), str.end(), writable); writable[str.size()] = '\0'; // don't forget the terminating 0 // don't forget to free the string after finished using it delete[] writable; Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.
** I am wondering why Alternative #2 chokes when I do :**
CURLcode retval = curl_easy_setopt(m_curl_handle, CURLOPT_URL, (char*)m_sUrl.c_str());
Is it necessary that I create a writable copy , like (char*) with std::string str; char * writable = new char[str.size() + 1]; std::copy(str.begin(), str.end(), writable); writable[str.size()] = '\0'; // don't forget the terminating 0
Any help is greatly appreciated
Aucun commentaire:
Enregistrer un commentaire