0

我正在寻找解决方案如何将网站读取到 system::String^

我发现 curl 到 std::string 的想法,但在转换链接器后有一些错误;/

这是我的代码:

using namespace std;

string contents; 
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream) 
{ 
    int numbytes = size*nmemb; 
    // The data is not null-terminated, so get the last character, and replace 
    // it with '\0'. 
    char lastchar = *((char *) ptr + numbytes - 1); 
    *((char *) ptr + numbytes - 1) = '\0'; 
    contents.append((char *)ptr); 
    contents.append(1,lastchar); 
    *((char *) ptr + numbytes - 1) = lastchar;  // Might not be necessary. 
    return size*nmemb; 
} 

..

      CURL* curl = curl_easy_init(); 
if(curl) 
    { 
       // Tell libcurl the URL 
       curl_easy_setopt(curl,CURLOPT_URL, "google.com"); 
       // Tell libcurl what function to call when it has data 
       curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data); 
       // Do it! 
       CURLcode res = curl_easy_perform(curl); 
       curl_easy_cleanup(curl); 
    textBox2->Text = gcnew String(contents.c_str());
    }
4

1 回答 1

2

如果您使用的是 .Net,为什么不使用它进行下载?

using namespace System;
using namespace System::Net;

int main(array<System::String ^> ^args)
{
    WebClient web;
    String^ text = web.DownloadString("http://www.google.de");
    Console::WriteLine(text);
    return 0;
}

如果由于某些原因必须使用 cURL,这应该可以

std::vector<char> LoadFromUrl(const char* url)
{
    struct Content
    {
        std::vector<char> data;
        static size_t Write(char * data, size_t size, size_t nmemb, void * p)
        {
            return static_cast<Content*>(p)->WriteImpl(data, size, nmemb);
        }

        size_t WriteImpl(char* ptr, size_t size, size_t nmemb)
        {
            data.insert(end(data), ptr, ptr + size * nmemb);
            return size * nmemb;
        }
    };

    Content content;

    CURL* curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &Content::Write);
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_perform(curl);

    content.data.push_back('\0');

    return content.data;
}

int main(array<System::String ^> ^args)
{
    auto content = LoadFromUrl("http://www.google.de");
    String^ text = gcnew String(&content.front());

    Console::WriteLine(text);
    return 0;
}
于 2012-06-11T11:26:25.510 回答