0

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

Cobra
  • 63
  • 1
  • 7
  • 1
    You're using [reserved identifiers](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Nov 30 '13 at 08:40

1 Answers1

1

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.

john
  • 85,011
  • 4
  • 57
  • 81
  • +1. This is a very common pattern in API design. If you need to be able to change the size of the object without breaking the API, then you have to export a create/free pair of functions, and indeed that pattern is used almost everywhere. – Nicholas Wilson Nov 30 '13 at 08:55
  • It works, what I wanted is dev = createDevice(). Now it is like dev->createDevice(). But I am ok with it. Thanks. – Cobra Nov 30 '13 at 08:58