Introduction: This article describes the methods of exporting STL classes and classes containing STL in DLLs. Example source code
DLLs cannot directly export generic templates (generalized template), so if you are exporting an STL class, the template must be instantiated (instantiated) first. In addition, if the exported STL class uses other STL classes, then these other classes must be exported at the same time. The only containers in the STL that can be exported are vectors, and other containers (such as map, set, queue, List, deque) cannot be exported because they contain nested classes.
To export an STL class:
In the DLL and EXE file, use the same version of the C run-time Library link. For example, use the Msvcrt.lib (release) link or both with the Msvcrtd.lib (Debug) link.
DLL, an instance of the template class is exported with __declspec (dllexport).
In the EXE file, import the STL class from the DLL with the __declspec (dllimport) and extern keywords.
It is important to note that when you export an STL container with a custom class as a template parameter, you must define the < and = operator for this custom type. For example, if you want to export the Std::vector<cperson> class, you must add the < and = = operator for CPerson. As follows:
//Export STL class STD:: vector < cperson >
class CPerson
{
Public:
int m_nAge;
char m_strName[40];
Public:
bool operator < (const CPerson& c) const
{{
return true;
}
bool operator == (const CPerson& c) const
{{
return true;
}
}
Exp template class vecdll API Std:: vector < cperson > / / the instantiation template class is displayed
Vecdll API int fnvecdll (STD:: vector < cperson > & vecper); / / export function
The reason for defining these operators is that all STL containers have "comparison" member functions that need to invoke the < and = = operator of the custom type. Normally, because these member functions are not used, they are not instantiated, so we generally do not need to define these two operators for CPerson. However, when the container class is instantiated, all of its member functions need to be instantiated, including its "compare" member function, so the cperson < and = = operator must be implemented. If CPerson does not care about the meaning of < and = = We can implement them as shown in the code above by simply returning true.
Exports a class with data members containing STL objects. The method is similar to the above. As shown in the following code:
EXPIMP_TEMPLATE template class VECDLL_API std::vector<int> //the instantiated std::vector<int>
class VECDLL_API CContainer
{
public:
std::vector<int> m_vecNum;
};
For a complete example, look at the instance code.
This article supporting source code