Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I need to export a class in C++ dll i've written. It isn't a subclass so it doesn't have to be exported along with its superclasses but it has data members and functions derived from various DLL such as setupapi.dll, user32.dll, MPUSBAPI.dll. Do i need to export them too or not? If so, how? Thanks in advance.
Posted
Updated 7-Feb-13 3:48am
v2

No, you just need to export the members that will need to be imported by users of your class.

See also Walkthrough: Creating and Using a Dynamic Link Library (C++)[^]
 
Share this answer
 
v2
You don't need to export the data members ( In fact if you export the class you can't export its members ). However the client code ( the bit that's importing on the other side ) needs to understand all the types used on the interface so it will need to include the headers e.g. windows.h that define them.

Be very careful to distinguish between exporting the class definition
class /*__declspec( dllexport/dllimport )*/ MY_API CMyClass
{
//...
};

and exporting an instance of the class
extern MY_API CMyClass AnInstance;

The first allows the client code to create its own instance of CMyClass, the second to see a single instance provided at module scope by the DLL.
If in doubt use the first technique.
One other thing: Don't have any public data members in the exported class. Use accessor functions Get, Set. It's more portable and safer that way especially when DLLs can have their own heaps and do their own memory management.
 
Share this answer
 
v2
Comments
Espen Harlinn 7-Feb-13 10:17am    
Good points
H.Brydon 7-Feb-13 13:27pm    
Yeah, +5 from me to you and Espen...
Sergey Alexandrovich Kryukov 7-Feb-13 17:57pm    
Right, a 5.
—SA
While Matthew covered most of the stuff you need to be aware of, there is one thing that may trip you up if you don't protect against it, and that's member alignment.
Have a look at #pragma pack[^]

In you header:
#ifndef __MYHEADER_H__
#define __MYHEADER_H__

#pragma pack(push,8) 

class MyClass
{
  char b;
  long long ll;
  bool b2; 
public:


  inline char getb() const { return b; }
  inline long long getll() const { return ll; }
};

#pragma pack(pop)

If client code uses a different alignment than your code was compiled with #pragma pack ensures that memory alignment stays as expected for your code.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Matthew Faithfull 7-Feb-13 10:32am    
That's a subtle one, I'll have to remember that.
Espen Harlinn 7-Feb-13 10:39am    
Thanks Matthew :-D
Sergey Alexandrovich Kryukov 7-Feb-13 17:57pm    
Agree, important to know; my 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900