C++ DLL question
-
Hello, I have a small DLL written in C++ that exports 4 functions. I call this DLL from my C# application and can call all these functions without any problem. I want to arrange for a DLL function to be called exactly once (sort of like a static constructor for the DLL). What is the best way to do something like this? Thanks, Keith
-
Hello, I have a small DLL written in C++ that exports 4 functions. I call this DLL from my C# application and can call all these functions without any problem. I want to arrange for a DLL function to be called exactly once (sort of like a static constructor for the DLL). What is the best way to do something like this? Thanks, Keith
What do you mean by "called exactly once"? You wanna prevent from "calling the dll function for a second time", or just make no effect when "calling the dll function for a second time"?
-
Hello, I have a small DLL written in C++ that exports 4 functions. I call this DLL from my C# application and can call all these functions without any problem. I want to arrange for a DLL function to be called exactly once (sort of like a static constructor for the DLL). What is the best way to do something like this? Thanks, Keith
You could try sticking the code you want executed exactly once in the DllMain for the DLL. Unfortunately there are some restrictions as to what can go in DllMain - don't do anything that might trigger another DLL load or it could go horribly wrong. Another option is to create an initialisation function and either just call it once or use a language feature of C# to make sure it's only called once. I don't know C# and it's idioms enough to suggest a relevant feature. You can make sure your initialisation function is only called once in the DLL using something like:
extern "C"
bool FOO_EXPORT initialise_foo_lib()
try
{
static bool initialised = false;
if( !initialised )
{
// Do rest of initialisation//... initialised = true; } return initialised;
}
catch( std::exception & )
{
return false;
}Cheers, Ash