Situation
External library (LibraryExternal) that I cannot change calls LoadLibrary on LibraryA. After it is succesfully loaded, it calls an exported function AExport which returns a pointer to ClassA, which is a static instance. Before AExport returns, it too loads a library via LoadLibrary, called LibraryB. After succesfull load, it calls an exported function BExport which in turn returns a pointer to a static instance ClassB.
IMPORTANT
LibraryA is a c++ dll compiled with vs2012 xp tools and LibraryB is a c++/cli dll also compiled with vs2012 xp tools.
All libraries share some other libraries which only define what ClassA and ClassB need to derive from, in order to make sense of the pointers returned by AExport and BExport. They are nothing more than stubs and do not matter in this question (Only pure virtual functions, no fields and nothing being done in ctor/dtor).
Result
When LibraryExternal gets unloaded via program exit, it calls FreeLibrary on LibraryA. This succesfully calls the destructor of ClassA which in turn frees the library LibraryB. But the destructor of ClassB is never run somehow.
Desired Result
Have ClassB destructor run
ClassA.h
#include <StubA.h>
class StubB;
class ClassA: public StubA
{
public:
ClassA();
~ClassA();
bool Initialize();
static ClassA &GetInstance()
{
static ClassA INSTANCE;
return INSTANCE;
}
private:
ClassA(ClassA const &);
void operator=(ClassA const&);
HMODULE wrapperModule;
StubB *wrapperPlugin;
};
ClassA.cpp
#include "ClassA.h"
#include <Windows.h>
// typedef WrapperPlugin *(*WrapperPluginInitType) (); This is normally in shared library
static const wchar_t *WRAPPER_MODULE_NAME = L"LibraryB.dll";
static const char *WRAPPER_MODULE_INIT_FUNCTION_NAME = "BExport";
ClassA::ClassA() :
wrapperModule(NULL),
wrapperPlugin(NULL)
{
}
ClassA::~ClassA()
{
if (this->wrapperModule != NULL)
{
FreeLibrary(this->wrapperModule);
}
}
bool CSharpBridge::Initialize()
{
this->wrapperModule = LoadLibraryW(WRAPPER_MODULE_NAME);
if (this->wrapperModule == NULL)
{
return false;
}
WrapperPluginInitType wrapperPluginInit = reinterpret_cast<WrapperPluginInitType>(GetProcAddress(this->wrapperModule, WRAPPER_MODULE_INIT_FUNCTION_NAME));
if (wrapperPluginInit == NULL)
{
return false;
}
this->wrapperPlugin = wrapperPluginInit();
if (this->wrapperPlugin == NULL)
{
return false;
}
return true;
}
extern "C"
{
__declspec(ddlexport) StubA *AExport()
{
if (!ClassA::GetInstance().Initialize())
{
return NULL;
}
return &ClassA::GetInstance();
}
}
ClassB.h
#include <StubB.h>
class ClassB : public StubB
{
public:
ClassB ();
~ClassB ();
static ClassB &GetInstance()
{
static ClassB INSTANCE;
return INSTANCE;
}
private:
ClassB (ClassB const &);
void operator=(ClassB const&);
};
ClassB.cpp
#include "ClassB.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
ClassB::ClassB()
{
std::ofstream myfile;
myfile.open("C:\\Users\\USERNAME\\Desktop\\test1.txt");
myfile << "ClassB::ClassB\r\n";
myfile.close();
}
ClassB::~ClassB()
{
std::ofstream myfile;
myfile.open("C:\\Users\\USERNAME\\Desktop\\test3.txt");
myfile << "ClassB::~ClassB\r\n";
myfile.close();
}
extern "C"
{
__declspec(dllexport) StubB *WrapperInit()
{
std::ofstream myfile;
myfile.open("C:\\Users\\USERNAME\\Desktop\\test2.txt");
myfile << "WrapperInit\r\n";
myfile.close();
return &ClassB::GetInstance();
}
}
Now I know with 100% certainty that ClassA ctor/dtor are called due to some LibraryExternal functions which give me some textual confirmation. And I do seem to be getting test1.txt and test2.txt generated. But NOT test3.txt.
After this I still need to create a managed reference to LibraryC which is a C# dll and 'destruct' that too when ClassB is being destructed.
It appears that you cannot use FreeLibrary on a library that is managed from an unmanaged library. Since the managed library will start the AppDomain for which the unmanaged library knows nothing about. The AppDomain keeps the library alive and therefor the destructor was never ran. See this answer.
Calling something from unmanaged to managed will still require some special attention since in not doing so will result in an exception: 0xC0020001: The string binding is invalid ! See this. What I did to fix the issue was having a static instance at ClassB scope and initializing it with the new operator in ClassB::GetInstance. Otherwise it would not be initialized at all. I then made a function ClassB::CleanUp in which I delete it. It is however important to mark the entire class (both header and source file) unmanaged with #pragma managed(push, off) and #pragma managed(pop).
To still be able to call managed methods/classes you have to make a function in the source file that has been surrounded with #pragma managed(push, on) and #pragma managed(pop). You can then call this function from the unmanaged class. This still seems strange to me, since that function is managed too?
Related
I am using VS2019
Trying to call a thread in DLL. to run two executables simultaneously with detach
following threads worked when I Run a normal c++ program
I get error
Error C3867 'myClass::runexeone': non-standard syntax; use '&' to create a pointer to member myGateway C:\Users\user\Downloads\Demo\myGateway\myplugin.cpp 21
plugin header
#include <windows.h>
#include <iostream>
#include <thread>
#define MYPLUGIN_EXPORT __declspec(dllexport)
extern "C"
{
MYPLUGIN_EXPORT void WINAPI OnStart();
}
pluging.cpp
#include "plugin.h"
using namespace std;
class myClass
{
public:
myClass()
{
}
~myClass()
{
}
void onStart()
{
std::thread(runexeone).detach();
std::thread(runexetwo).detach();
}
void runexeone()
{
int exerunpne = system("cmd /C \"%MY_ROOT%\\bin\\Mytest.exe\" -ORBEndpoint iiop://localhost:12345 -d");
}
void runexetwo()
{
int exeruntwo = system("cmd /C \"%MY_ROOT%\\bin\\Mytest_2.exe\" -ORBEndpoint iiop://localhost:12345 -d");
}
};
myClass& getmyclass()
{
static myClass myclass;
return myclass;
}
MYPLUGIN_EXPORT void WINAPI OnStart()
{
getmyClass().onStart();
}
The problem is that runexeone is an unqualified name of a member function, and std::thread needs something executable. runexeone isn't. VC++ tries to guess from context what you mean, but the suggestion isn't enough. Even if you had written &myClass::runexeone, it still wouldn't have worked, because myClass::runexeone also needs a this pointer. You can fix the latter problem by making it static.
Compiler suggestions work best when there's just one problem.
As MSalters already mentioned, you provided the wrong data type for the functor for std::thread. If you cannot make the method static (which you can actually at least for the current state of your code, but to let this not be unstated here), you can do this
void onStart()
{
std::thread(std::bind(&myClass::runexeone, this)).detach();
}
But be careful about the lifetime/existence of your object/this!
I have implemented singleton of Meyers and four function to work with it. For example:
//A.h
class A
{
private:
Device d;
public:
A(){//...}
~A(){d.release();}
}
My class singleton Meyers
//Controller.h
class Controlle
{
private:
//some members
A m_member;
Controller();
Controller(const Controller&);
Controller& operator=(const Controller&);
public:
static Controller& GetInstance()
{
static Controller instance;
return instance;
}
}
And interface for working the class of Controller
extern "C" API Result InitDevice(const ParamsDevice* param);
extern "C" API Result InitAlgorithm(const ParamAlgorithm* param);
extern "C" API Result Operation_1();
extern "C" API Result Operation_2();
I build the library and get the Controller.dll and Controller.lib files. Library is shared lib.
Then I create a program where Controller.dll is used (implicit). Runtime library exception is thrown after program termination. I compiled the library in debug to check where the exception is thrown from.
I am getting the exception from comip.h file from method Release() class
template<typename _IIID> class _com_ptr_t
{
public:
// Declare interface type so that the type may be available outside
// the scope of this template.
//
typedef _IIID ThisIIID;
typedef typename _IIID::Interface Interface;
........
// Provides error-checking Release()ing of this interface.
//
void Release()
{
if (m_pInterface == NULL) {
_com_issue_error(E_POINTER);
}
else {
m_pInterface->Release();
m_pInterface = NULL;
}
}
}
I think that when the program terminates, the resources of static objects that are used in the library are incorrectly released. If I replace the singelton Meyers with a classic singelton and create methods for explicitly freeing up the memory of a static pointer, then everything works well. Could you help me explain this effect?
I think there is an answer to my question, but it is not complete for me and I cannot understand
https://stackoverflow.com/a/50644725/13970084
P.S. Sorry for my English. English isn't my native language.
So I've got this interface class that I include, both in the dll and the client project
// InterfaceClass.h
#pragma once
class InterfaceClass
{
public:
virtual void Update() = 0;
};
This is the dll class that calls one of its own methods inside update
// DLLClassThatDoesSomething.cpp
#include "InterfaceClass.h"
#include <iostream>
#include <string>
class __declspec(dllexport) DLLClass : public InterfaceClass
{
public:
void Update()
{
std::cout << this->GetString();
}
std::string& GetString()
{
std::string thestring = "bruhmoment";
return thestring;
}
};
extern "C"
{
__declspec(dllexport) InterfaceClass* CreateInstance()
{
return new DLLClass();
}
}
And this is the "Client" project
// main.cpp
#include "InterfaceClass.h"
#include <Windows.h>
typedef InterfaceClass* (__cdecl *Class) ();
int main()
{
HINSTANCE dll = LoadLibrary(L"DLLClass.dll");
Class klass = (Class)GetProcAddress(dll, "CreateInstance");
InterfaceClass* IKlass = klass();
IKlass->Update();
FreeLibrary(dll);
return 0;
}
The moment I call IKlass->Update() I get an exception for Access Memory Violation because of the DLLClass calling its own method.
I haven't tried anything since I barely know how to load a DLL on runtime and I've used this nifty tutorial
How can I let it call the method and not get thrown an exception? I'm trying to let ppl that will create mods for my game create their own mods with their custom classes for bosses, mobs and etc. in DLLs.
EDIT:
Turns out it was a syntax mistake on my end. Instead of return new DLLClass;, it had to be return new DLLClass();. After fixing it, it works as intended.
You return a reference to a local variable thestring, and by the time you try to access it in
std::cout << this->GetString(), referenced data is already destroyed. In fact, it is destroyed right after the end of enclosing scope of compound statement where the variable was declared.
It may "appear" to work sometimes due to the stack not being overwritten yet, but eventually it will fail miserably like it did in your case. This triggers UB (undefined behavior).
I have the following classes in my code.
In other words, There is a static object (singletone) which creates thread in CTor, and when its DTor is called, it has some work to be done in the context of this thread (DTor puts some jobs for the thread).
The problem that i face is that when the DTor of B is called there are no other threads running in the process - seems like this thread is killed by process cleanup before calling the destructor of class B.
Anyone knows why this happens? and how to avoid it?
UPD: The problems occures only when Singleton is created from DLL. All works fine when Singleton is created from the same executable.
I am using VS2017
Singleton.dll (A.h + A.cpp)
A.h -->
#pragma once
#include <thread>
class __declspec(dllexport) A
{
public:
static A* instance();
A();
~A();
private:
bool stopFlag;
std::thread mThread;
};
A.cpp
#include "stdafx.h"
#include <thread>
#include "A.h"
using namespace std;
A::A()
{
mThread = std::thread([this] { while (stopFlag == false) { } });
}
A::~A()
{
stopFlag = true;
mThread.join();
}
A* A::instance()
{
static A self;
return &self;
}
================================================================================
Executable which uses DLL
main.cpp
#include "stdafx.h"
#include "A.h"
int main()
{
auto a = A::instance();
return 0;
}
Updated with the compilable code. Now if you compile the first two files as DLL, and then put breakpoint in A's destructor, you will see that thread with lambda function does not exists....
UPDATE: Found an answer by myslef. In Windows, static object from DLL are unloaded ay very last point when all threads are already cleaned up
https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx
Found an answer by myslef. In Windows, static object from DLL are unloaded ay very last point when all threads are already cleaned up https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx
I would like to understand the DLL mechanism and what the compiler does when I loads the DLL at run-time (i.e. I will not use the generated .lib).
Consider the following C++ code:
DLL interface header file
#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
class MYDLL_API Base
{
public:
Base();
virtual ~Base();
virtual int get_number() const;
virtual const char* what() const = 0;
private:
int i_;
};
class MYDLL_API Child : public Base
{
public:
Child();
virtual ~Child();
virtual int get_number() const override;
virtual const char* what() const override;
private:
int j_;
};
extern "C" {
MYDLL_API Base* __cdecl initializeObject();
}
DLL implementation source file
#include "MyDLL.hh"
Base::Base()
: i_(42)
{}
Base::~Base()
{}
int Base::get_number() const
{
return i_;
}
Child::Child()
: Base()
, j_(24)
{}
Child::~Child()
{}
int Child::get_number() const
{
return j_;
}
const char* Child::what() const
{
return "Hello!";
}
Base* initializeObject()
{
return new Child();
}
The goal of this DLL is to have a common interface defined by the Base class, but it allows specifics implementations compiled in different DLLs that are loaded at runtime (here the Child class is exposed for the purpose of the example).
At this stage, if I naively include the DLL's header:
#include "MyDLL.hh"
int main()
{
Base* b = new Child();
std::cout << b->get_number() << std::endl;
std::cout << b->what() << std::endl;
delete b;
getchar();
return 0;
}
The linker complains LNK2019 and LNK2001 errors: it can not resolves symbols. So, it behaves as expected (I did not use the .lib).
Consider now, the following code that I use to load the DLL at runtime:
#include "MyDLL.hh"
typedef Base* (*initFuncType)();
int main()
{
HINSTANCE handle = LoadLibrary(L"MyDLL.dll");
initFuncType init = nullptr;
init = (initFuncType)(GetProcAddress(handle, "initializeObject"));
if (init)
{
Base* b = init(); //< Use init() !
std::cout << b->get_number() << std::endl;
std::cout << b->what() << std::endl;
delete b;
}
getchar();
FreeLibrary(handle);
return 0;
}
This time it works, the linkage is done.
1st question: What happened? What changed for the compiler and the linker? The use of the function pointer on initializeObject() solves the problem.
The other issue I do not understand well is when I remove virtual and override of get_number():
int get_number() const;
I have a LNK2019 error because of the unresolved Base::get_number(void) const symbol in the _main function. I understand that the virtual keyword will resolve the member function dynamically (at run-time). In our case, the DLL is not loaded yet, the get_number symbol is not available.
2nd question: Does this means that methods must always be virtual using DLL run-time linking?
3rd question: How can I have the C++ function exportation with the Windows API? So that I could remove the extern "C" { ... } stuff.
Thanks for your reading! I hope I will read interesting answers! :)
There are two ways to link dll files.
The 2nd way (the way it works) is the C Binding approach, where you query the dll for a specific function name and it returns a functor to you.
Using the 2nd way you won't be able to extend the base classes, since they are not defined (you don't have any code to be copy pasted so to speak at linkage time).
In order to have a dll who's classes can be extended, you will need to use dynamic binding. You need to compile your .dll and also provide a Symbols Library (or an export library). You have this option in VS studio in project properties.
The mechanism is as following :
Compile Dll project -> output : myLib.dll , myLib.lib
Use exported symbols from myLib.lib inside your main project (main project takes myLib.lib as dependency)
at runtime,due to the binding, your program will know it requires myLib.dll to work so it will load it (if found, else you get runtime error)
Another advantage of using Export Library is that you can export C++ functions (which are mangled on export).
It's very hard to have C Binding on mangled functions.
C Binding on the otherhand, compared to the dynamic binding, won't make your program scream if myLib.dll isn't found , you will just get a null pointer to function.