Не удалось найти точку входа в библиотеке динамической компоновки - c ++

Я создал проект DLL на Visual C ++ и хотел использовать cpprestsdk/casablanca.

Затем я создал файл заголовка RestWrapper.h:

#pragma once

namespace mycpprest
{
    class RestWrapper
    {
    public:
        static __declspec(dllexport) void TestApi();
    };
}

И RestWrapper.cpp исходный файл:

#include "stdafx.h"
#include "RestWrapper.h"

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/json.h>

using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;

namespace mycpprest
{
    void RestWrapper::TestApi()
    {
        auto fileStream = std::make_shared<ostream>();

        // Open stream to output file.
        pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
        {
            *fileStream = outFile;

            // Create http_client to send the request.
            http_client client(U("http://13.231.231.252:3000/api/individual_employment_setting/detail/172"));

            // Build request URI and start the request.
            //uri_builder builder(U("/search"));
            //builder.append_query(U("q"), U("cpprestsdk github"));
            return client.request(methods::GET);
        })

        // Handle response headers arriving.
        .then([=](http_response response)
        {
            printf("Received response status code:%u\n", response.status_code());

            // Write response body into the file.
            // return response.body().read_to_end(fileStream->streambuf());
            stringstreambuf buffer;
            response.body().read_to_end(buffer).get();

            //show content in console
            printf("Response body: \n %s", buffer.collection().c_str());

            //parse content into a JSON object:
            //json::value jsonvalue = json::value::parse(buffer.collection());

            return  fileStream->print(buffer.collection()); //write to file anyway
        })

        // Close the file stream.
        .then([=](size_t)
        {
            return fileStream->close();
        });

        // Wait for all the outstanding I/O to complete and handle any exceptions
        try
        {
            requestTask.wait();
        }
        catch (const std::exception &e)
        {
            printf("Error exception:%s\n", e.what());
        }
    }
}

Когда я его строю, успех строится.

Затем я создал Windows Console Application в Visual C ++, чтобы протестировать созданный мной проект DLL.

Копирую MyCpprestDll.dll, MyCpprestDll.lib and RestWrapper.h из MycppestDll project в DllTest project.

Затем в проекте DllTest properties, в Linker->input->Additional Dependencies: я добавил MyCpprestDll.lib

А вот код DllTest.cpp:

#include "stdafx.h"
#include "RestWrapper.h"
#include <iostream>

using namespace mycpprest;

int main()
{
    RestWrapper::TestApi();
    system("PAUSE");
    return 0;
}

У него нет ошибки компиляции, но при запуске ошибка говорит:

The procedure entry point ?TestApi@RestWrapper@mycpprest@@SAXXZ could not be located in the dynamic link library

введите описание изображения здесь

Я попытался найти связанные с этим проблемы, но не знаю, как это сделать и что настроить для моей точки входа в моем проекте dll.


person noyruto88    schedule 13.04.2018    source источник


Ответы (2)


Вам нужно использовать dllexport при создании своей библиотеки DLL, но dllimport, когда вы включаете ее в другой проект.

В этом ответе показано, что для создания это работает.

person Sean    schedule 13.04.2018

В заголовочном файле RestWrapper.h сделайте что-нибудь, как показано ниже. Обратите внимание, что вы должны использовать __declspec (dllimport) для импортируемого исполняемого файла для доступа к общедоступным символам данных и объектам библиотеки DLL. Также убедитесь, что вы определили макрос RestWrapper_EXPORTS в C / C ++ -> Preprocessor-> Preprocessor Definitions в свойствах вашего проекта DLL.

#ifdef RestWrapper_EXPORTS
#define RestWrapper_APIS __declspec(dllexport)
#else
#define RestWrapper_APIS __declspec(dllimport)
#endif

namespace mycpprest
{
 // This class is exported from the RestWrapper.dll
 class RestWrapper 
 {
   public:
    static RestWrapper_APIS void TestApi();     
 };
}

Перестройте свой проект DLL. Никаких изменений в вашем проекте DllTest не требуется, просто скомпилируйте проект DllTest, используя обновленные файлы RestWrapper.h и RestWrapper.lib.

person Amit Rastogi    schedule 14.04.2018