2017-02-24 54 views
0

我試圖學習如何在C函數中正確使用LoadLibrary,但是遇到了困難,並且沒有太多好的教程需要遵循。我創建了一個簡單的C程序,它使用libCurl庫成功獲取網站的HTML並將其打印到控制檯。我現在試圖使用LoadLibraryGetProcAddresslibcurl.dll重新實現相同的功能。從C中LoadLibrary加載函數傳回數據?

如何從加載到內存的函數中傳回數據?

下面發佈的是使用.lib工作的函數,隨後函數試圖使用未能編譯的DLL。

這是我的工作程序:

#include "stdafx.h" 
#include "TestWebService.h" 
#include "curl/curl.h" 

int main(int argc, char **argv) 
{ 
    CURL *curl; 
    CURLcode res; 

    curl = curl_easy_init(); 
    if (curl) { 

     struct string s; 
     init_string(&s); 

     curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); 
     /* example.com is redirected, so we tell libcurl to follow redirection */ 
     curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); 
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); 
     curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); 

     /* Perform the request, res will get the return code */ 
     res = curl_easy_perform(curl); 
     /* Check for errors */ 
     if (res != CURLE_OK) 
      fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); 

     /* always cleanup */ 
     printf("%s\n", s.ptr); 
     free(s.ptr); 
     curl_easy_cleanup(curl); 
    } 

    return 0; 
} 

這是我試圖複製只使用LoadLibrary相同的功能(即不使用libCurl.lib)。但我收到以下錯誤消息,無法確定原因。

1) a value of type "CURL" cannot be assigned to an entity of type "CURL *" 
2) '=': cannot convert from 'CURL' to 'CURL *' 

#include "stdafx.h" 
#include "TestWebService.h" 
#include "curl/curl.h" 

typedef CURL (*CurlInitFunc)(); 

int main(int argc, char **argv) 
{ 
    HINSTANCE   hLib = NULL; 
    hLib = LoadLibrary("libcurl.dll"); 
    if (hLib != NULL) 
    { 
     CURL *curl; 
     CurlInitFunc _CurlInitFunc; 
     _CurlInitFunc = (CurlInitFunc)GetProcAddress(hLib, "curl_easy_init"); 
     if (_CurlInitFunc) 
     { 
      curl = _CurlInitFunc(); 

     } 

    } 
    return 0; 
} 
+1

簡單:'typedef的捲曲( * CurlInitFunc)();' - >'typedef CURL *(* CurlInitFunc)();' –

+1

細節:最後不要忘記'FreeLibrary(hLib)'。 –

+0

另一個細節:將'_CurlInitFunc'重命名爲'_curl_easy_init',你的代碼將更具可讀性。 –

回答

1

這條線:

typedef CURL (*CurlInitFunc)(); 

聲明一個指針到返回CURL的功能。但curl_easy_init()的原型爲:

CURL *curl_easy_init(); 

這意味着它返回一個指針CURL,即CURL*

因此,正確的聲明是:

typedef CURL *(*CurlInitFunc)();