I read some documents which gives simple examples on functions compatible with C.
__declspec(dllexport) MyFunction();
I'm okey with that. I write a small application uses the functions of this dll. I used explicit linking with
LoadLibrary()
function. C style functions work without problems. But when i write my class as
namespace DllTest
{
class Test
{
public:
__declspec(dllexport) Test();
__declspec(dllexport) void Function( int );
__declspec(dllexport) int getBar(void);
private:
int bar;
};
}
#endif
it compiles well and Dll is created. While working with C style functions i was simply taking a function pointer from LoadLibrary() and GetProcAddress(...) functions.
My previous usage is
typedef void (*Function)(int);
int main()
{
Function _Function;
HINSTANCE hInstLibrary = LoadLibrary(TEXT("test.dll"));
if (hInstLibrary)
{
_Function = (Function)GetProcAddress(hInstLibrary,"Function");
if (_Function)
{
// use the function
But now i have no idea how can i instantiate my class? How can i use explicit linkage or implicit linkage?
Any help with a code sample would be appreciated.
Think of namespaces as "folders" that contain one or more classes, and that might be defined in one or more assemblies (DLLs). For example, Classes inside the System namespace are defined in 2 assemblies (DLLs): mscorlib. dll and System.
Use the C++ keyword using to import a name to the global namespace: using namespace std; printf("example\n"); Use the compiler option --using_std .
The dllexport and dllimport storage-class attributes are Microsoft-specific extensions to the C and C++ languages. You can use them to export and import functions, data, and objects to or from a DLL.
Yes you can surely move ahead with this idea. If we use same namespace name in different files those get automatically clubbed into one.
If you're trying to instantiate a class, then you need to know its structure on compilation time. You can achieve this by creating an abstract class that defines the instance methods that the imported class will have to redefine. For example:
//interface.h
class TestInterface
{
public:
virtual void Function( int ) = 0;
virtual int getBar(void) = 0;
};
Afterwards, in your DLL, you can include interface.h, inherit TestInterface and redefine the pure-virtual methods:
//test.h
namespace DllTest {
class Test : public TestInterface
{
public:
Test();
void Function( int );
int getBar(void);
private:
int bar;
};
};
You could then define a function in your DLL which allocates a Test object:
extern "C" __declspec(dllexport) TestInterface *allocate_test() {
return new DllTest::Test();
}
And finally, when you import the DLL, look for the symbol "allocate_test" and use it:
TestInterface *(*test_fun)() = (TestInterface *(*test_fun)())GetProcAddress(hInstLibrary,"allocate_test");
TestInterface *test_ptr = test_fun();
test_ptr->Function(12); //use you object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With