Cobra
Cobra

Reputation: 63

Dynamic Link Library function export

First the main.h file - main.h

#ifndef __MAIN_H__
#define __MAIN_H__

#include <iostream>

#ifndef _BUILD_DLL
#define XXX_API __declspec(dllexport)
#else
#define XXX_API __declspec(dllimport)
#endif

#include "device.h"

// Core functions
namespace xxx
{
    XXX_API void createDevice(int w, int h);
}

#endif // __MAIN_H__

main.cpp

#define _BUILD_DLL

namespace xxx
{

XXX_API void createDevice(int w, int h)
{
    Device dev;
    dev.createDevice(w, h);
}

}

device.h

#ifndef __DEVICE_H__
#define __DEVICE_H__

namespace xxx
{

class Device
{
public:
    Device();
    virtual ~Device();

    XXX_API void createDevice(int width, int height);

}; // end of class

} // end of namespace

#endif

device.cpp

#include "main.h"

namespace xxx
{

   Device::Device()
   {
   }

   Device::~Device()
   {
   }

   XXX_API void Device::createDevice(int width, int height)
   {
    std::cout << "Width: " << width << std::endl;
    std::cout << "height: " << height << std::endl;
   }

} // end of namespace

This are the files that create the dll and library. And here is the test.cpp that creates the application which calls that lib functions-

#include "main.h"

int main()
{
    xxx::createDevice(800, 600);

    std::cout << "Press the ENTER key to exit.";
    std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);

    return 0;
}

As you can see I am calling createDevice(int, int) to create the device. What I want to know is how do I export the dll calls so that I can get a pointer to that device to call its member function from test.cpp. like this -

#include "main.h"

int main()
{
    xxx::Device* dev = createDevice(800, 600);

    std::cout << "Press the ENTER key to exit.";
    std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);

    return 0;
}

Thanks in advance

Upvotes: 0

Views: 218

Answers (1)

john
john

Reputation: 88007

Change createDevice to this

XXX_API Device* createDevice(int w, int h)
{
    Device* dev = new Device();
    dev->createDevice(w, h);
    return dev;
}

Presumably you should to add a destroyDevice function to free the memory.

Upvotes: 1

Related Questions