2016-08-27 88 views
1

我試圖檢索與的libevent註冊的回調中要求的原始連接信息:「結構的正向宣言」,而獲取libevent的連接信息

#include <evhttp.h> 
#include <iostream> 

//Process a request 
void process_request(struct evhttp_request *req, void *arg){ 

    //Get the request type (functions correctly) 
    std::cout << req->type << std::endl; 

    //Get the address and port requested that triggered the callback 
    //When this is uncommented, the code no longer compiles and throws 
    //the warning below 
    struct evhttp_connection *con = req->evcon; 
    std::cout << con->address << con->port << std::endl; 
} 

int main() { 

    //Set up the server 
    struct event_base *base = NULL; 
    struct evhttp *httpd = NULL; 
    base = event_init(); 
    if (base == NULL) return -1; 
    httpd = evhttp_new(base); 
    if (httpd == NULL) return -1; 

    //Bind the callback 
    if (evhttp_bind_socket(httpd, "0.0.0.0", 12345) != 0) return -1; 
    evhttp_set_gencb(httpd, process_request, NULL); 

    //Start listening 
    event_base_dispatch(base); 
    return 0; 
} 

不過,我收到以下錯誤:

$g++ -o basic_requests_server basic_requests_server.cpp -lpthread -levent -std=c++11 

basic_requests_server.cpp:45:18: error: invalid use of incomplete type ‘struct evhttp_connection’ 
    std::cout << con->address << con->port << std::endl; 
      ^
In file included from /usr/include/evhttp.h:41:0, 
      from basic_requests_server.cpp:1: 
/usr/include/event2/http.h:427:8: error: forward declaration of ‘struct evhttp_connection’ 
struct evhttp_connection *evhttp_connection_base_new(

爲什麼我不能訪問這個結構的元素?

+0

@skypjack:作出回答 –

+0

@MartinBonner不夠公平。完成。 – skypjack

回答

2

Why can't I access the elements of this struct?

據我瞭解,連接(即struct evhttp_connection)是指用於僅供內部使用。
你不應該直接使用它們或它們的字段,但你可以得到一個指向連接的指針並傳遞指針。
它的目的是爲了避免客戶端綁定到連接的內部表示(這樣可以以這種方式默默改變)。
這就是爲什麼該類型沒有實際暴露。你可以把它看作是一個不透明指針你不允許取消引用。

請參閱here的深入解釋。