c# - Visual Studio C++ 类库中的回调

标签 c# c++ visual-studio-2013

我需要从 C# 调用 native C++。 C++ 库中的一种方法需要读取网页内容 - 我决定通过 cURL 库来完成。我创建了一个 Visual C++ -> CLR -> 类库 项目,现在我的库如下所示:

#pragma once    
#include <stdio.h>
#include <string>
#include <curl/curl.h>

using namespace System;

namespace HtmlCppParser {

    public ref class HtmlCppParser
    {
    public:
        String^ GetContent(String^ url){
            CURL *curl;
            CURLcode res;
            String^ content;

            curl = curl_easy_init();
            if (curl) {
                curl_easy_setopt(curl, CURLOPT_URL, url);
                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, this->write_data);
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
                res = curl_easy_perform(curl);
                curl_easy_cleanup(curl);

                return content;
            }
        }

    private:
        size_t write_data(void *contents, size_t size, size_t nmemb, void *userp)
        {
            ((std::string*)userp)->append((char*)contents, size * nmemb);
            return size * nmemb;
        }
    };
}

当我编译这个时,我得到C3867 错误:

错误 C3867:HtmlCppParser::HtmlCppParser::write_data:函数调用缺少参数列表;使用“&HtmlCppParser::HtmlCppParser::write_data”...

我的错误在哪里?

最佳答案

我认为最简单的解决方案是使 write_data 成为“经典”C 函数(将其移出 HtmlCppParser 类)并替换 this->write_data by &write_data,因为您似乎通过 userp 指针接收了所需的一切。

并且您应该注意通过 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content); 提供 System::String 但将其转换为 std::stringwrite_data 中。您也应该在 GetContent 中使用 std::string 或者可能将两者替换为 System::Text::StringBuilder .

关于c# - Visual Studio C++ 类库中的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289829/

相关文章:

c++ - 使用 Opencv 检测文本上的角点

c++ - "gdb"调试器奇怪地跳过断点

c# - 任务错误处理-Visual Studio停止

unit-testing - 在 VS 2013 中使用 HttpClient 代理类对 Web API 进行单元测试

azure - 使用 Visual Studio 2013 部署时未复制相关依赖项 (DLL)

具有接口(interface)混淆的 C# 通用 ClientBase

javascript - 如何读取 .NET WebAPI 5.2.2 上的 javascript FormData 对象

c# - 设置默认 "ok"和 "cancel"按钮

c++ - Ncurses - "move"及其衍生物删除屏幕内容

c# - 使用 Entity Framework 代码优先创建表、运行时