Rasmus
Rasmus

Reputation: 75

Creating object from class with __declspec(dllexport)

//file.h
# define PartExport __declspec(dllexport)
namespace Part{

class PartExport MyClass : public data::anotherClass{
  MyClass();
  void read();
};
}

I want to access this function by doing this below. Visual studio suggests to do "Part::read();" and f12 to that function works.

//main.cpp
#include <file.h>

int main(){

   Part::read();
   return 0;
}

But when compiling it complains about syntax errors because it thinks that PartExport is the class name. How can I access this function or create an object of MyClass?

edit: I realized that all the syntax errors on the class comes from the #include . I dont know what that means

Upvotes: 0

Views: 1525

Answers (2)

A.Franzen
A.Franzen

Reputation: 745

What you want to access is NOT a function, but a member-function. As such you have to specify which class it is a member of.

And as you haven't declared it static which would have made it similiar to a function, you even have to instantiate one of your MyClass before you can access it. (A non-static function has a 'this'-pointer, without an instance of your class there would be no 'this')

The namespace 'Part' is just another wrapper around your class.

To Access something in a namespace you do something like this:

Part::somethinginmynamespace

To call a function in a namespace you do

Part::somefunction();

To access a static memberfunction you use

Part::SomeClass::SomeStaticFunction();

To access a non-static member function you do:

Part::Someclass myinstance;
myInstance.myFunction();

If you get errors on a define, and the compiler thinks it's a classname, then the define is undefined. Maybe you put it in a comment, or the upper/lowercase is wrong.

Upvotes: 1

dkg
dkg

Reputation: 1775

Your class MyClass is exported, hence you should write in your main :

Part::MyClass myClass;
myClass.read();

If you want to call your function as you actually do in your main, you should write in your file.h :

namespace Part{

  void PartExport read();

}

But in this case you will lose your class encapsulation.


Another thing : to create your dll you have to specify the __declspec(dllexport) to export the function in the library.

But when your are using it, you should not tell your executable that you want to export this function as it was already exported in your library.

I advise you to compile your dll defining this macro in your project : PART_EXPORT_DLL

Then write it like this in your file.h:

//file.h
#ifdef PART_EXPORT_DLL
#    define PartExport __declspec(dllexport)
#else
#    define PartExport __declspec(dllimport)
#endif
namespace Part{

    class PartExport MyClass : public data::anotherClass{
      MyClass();
      void read();
    };
}

And when you want to import it, be sure not to define PART_EXPORT_DLL

Upvotes: 2

Related Questions