Pointers in and out of DLLs - windows

Is it possible to pass a pointer to an object into a DLL, initialize it, and then use the initialized pointer in the main application? If so how? Are there any good articles on the subject, perhaps a tutorial?
I have read this article http://msdn.microsoft.com/en-us/library/ms235460.aspx But that did not seem to get me any where. Maybe I am misinterpreting it...

Yes, this is fine, but assuming your DLL has dynamically allocated the data being pointed to by the buffer, you must be careful about how you free it. There are a few ways to deal with this:
The DLL documents a method by which one should free the data (i.e., CoTaskFree)
The DLL exposes a function that should be called to later free the data
The DLL and the caller are using a common DLL-based runtime; this allows the caller to use the C++ delete operator

Yes.
Assuming you are using Microsoft Visual Studio as your development environment you can export a class rather directly from a dll. Add a define to your dll project something like BUILDING_THE_DLL and the following code snippit will export a c++ class wholesale from the dll.
#ifdef BUILDING_THE_DLL
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif
class EXPORT DllClass
{
....
};
This is a highly coupled solution and only works if you build the application and its dll using the same development environment, and rebuild both whenever the class definition changes in any way. this method is heavilly used by the MFC library.
To achieve a greater independence between the dll and app, one typically defines a relatively immutable interface and uses that to make builds more independent, and possibly use different build environments.
An implementation in your dll would look something like this:
struct IMyInterface {
virtual void Destroy() =0;
virtual void Method() = 0;
};
class MoDllObject : public IMyInterface
{
// implementation
};
bool EXPORT DllGetInterface(IMyInterface** ppOut)
{
*ppOut = new MyDllObject();
return true;
}

Related

Should I always use the override contextual keyword?

I know that the override contextual keyword was introduced to write safer code (by checking for a virtual function with the same signature) but I don't feel good about it, because it seems to be redundant for me to write override every time I want to override a virtual function.
Is it a bad practice to not use override contextual keyword for 99% of cases? Why/when should I have to use it (a compiler warning is not enough when we are hiding a virtual function mistakenly)?
EDIT: In other words; what is the advantage of using the override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly in C++03 (without using override contextual keyword)?
The override keyword is totally useful and I would recommend using it all the time.
If you misspell your virtual function it will compile fine but at runtime the program will call the wrong function. It will call the base class function rather than your override.
It can be a really difficult bug to find:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual int func()
{
// do stuff for bases
return 3;
}
};
class Derived
: public Base
{
public:
virtual int finc() // WHOOPS MISSPELLED, override would prevent this
{
// do stuff for deriveds
return 8;
}
};
int main()
{
Base* base = new Derived;
std::cout << base->func() << std::endl;
delete base;
}
Annotations are what you call contextual keywords, they serve as clarification, to make sure anyone who reads the code realizes it is a function that overrides a function in a superclass or a interface.
The compiler can also give a warning if the originally overridden feature was removed, in which case you might want to think about removing your function as well.
As far as I know, nothing bad happens if you ommit anotations. It's neither right nor wrong. Like you stated correctly already: annotations are introduced to write safer code.
However: They won't change your code in any functional way.
If you work as a single programmer on your own project it might not matter wheter you use them or not. It is however good practice to stick to one style (i.e. either you use it, or you don't use it. Anything inbetween like sometimes using it and sometimes not only causes confusion)
If you work in a Team you should discuss the topic with your teammates and decide wheter you all use it or not.
What is the advantage of using override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly
Nearly none!?
But:
It depends on how much warnings will be accepted by your build rules. If you say, every warning MUST be fixed, you will get the same result UNTIL you are using a compiler which give you the warning.
We have decided to always use override and remove virtual on overriding methods. So the "overhead" is zero and the code is portable in the meaning of "give an error" on misuse.
I personally like this new feature, because it makes the language clearer. If you say this is an override, it will be checked! And if we want to add a new method with different signature, we will NOT get a false positive warning, which is important in your scenario!

SmartPointer from DLL: where to construct & destruct

I'm currently remodelling a dynamic library project and removed a lot of STL and other dependencies from its header resulting in conflicting implementations between different toolchains.
The DLL Interface now only contains plain C-types and custom types whom implementation depends solely on the DLL code. But now I'm stuck with two remaining points.
The DLL should return some sort of reference counting smart pointer (with a weak pointer option)
Managing construction and destruction between the DLL boundaries. This more or less looks like this.
.
#include <memory>
class Config;
typedef std::shared_ptr<Config> ConfigPtr;
class CONFIGAPI_DLL Config
{
public:
///...
ConfigPtr getNewNode( char const* query = "." )
{
// construct obj in dll, but construct shared_ptr in header
return ConfigPtr( _constructgetNewNode(query) );
}
ConfigPtr getNewNodeFromHeader( char const* query = "." )
{
// construct obj and shared_ptr in header
auto obj = new Config;
obj->_init(query);
return ConfigPtr( obj );
}
private:
Config* _constructNewNode( char const* query = "." );
void _init( char const* query = "." );
};
I was thinking by creating the share_ptr at the dll headers (getNewNode) it would prevent mixed implementations of std::shared_ptr ...but I don't know if that is a good idea?
But I also construct the new object inside the DLL (_constructNewNode) and this means it should also be destructed there?
I tried to construct it in the headers and so in the user code scope (getNewNodeFromHeader)... this shouldn't cause problems?
The downside is I still export the C++11 header and rule out all older compilers. Is it possible to export the shared_ptr type from the dll as unconflicting code but still be compatible with std::shared_ptr?
thanks!
I suppose you want to mix creation and destruction of the objects (Config and the shared_ptr). If the DLL client is not compiled with the same version and configuration of the compiler you would be in troubles (for example, mixing debug and release modules). The main problem I see here: there is not any type of standard ABI for C++.
I was thinking by creating the share_ptr at the dll headers
(getNewNode) it would prevent mixed implementations of std::shared_ptr
...but I don't know if that is a good idea?
If you define your header file to create the shared_ptr, that would be OK if only a module use that header file. I mean, if the shared_ptr is not to be used for the content of the DLL, for example. BUT if other client module (a binary module, like other DLL) use also that header, you must be sure they are compiled with the same compiler and compiling configuration. If you have not that guarantee, then is not good idea.
But I also construct the new object inside the DLL (_constructNewNode)
and this means it should also be destructed there?
If you construct the object inside the DLL, you'll be better destroying inside the DLL. How to do that? specifying a deleter at shared_ptr construction. Something like
struct ConfigDeleter {
void operator()(Config* c) {
c->destroy(); // or as you want to implement it.
};
typedef std::shared_ptr<Config, ConfigDeleter> ConfigPtr;
I tried to construct it in the headers and so in the user code scope
(getNewNodeFromHeader)... this shouldn't cause problems?
As before, it depends if you can guarantee all modules are homogeneous (same compiler version and configuration, library, etc.). But of you want to implement as that, do it well:
// construct obj and shared_ptr in header
auto obj_ = make_shared<Config>();
obj_->init(query);
It is exception-safe and more efficient: just one allocation to store the object and the reference, instead two allocations in your sample.
If you want your code be safe for mixing modules, implement all allocations (shared_ptr included) into the DLL, if they are shared. Exports a "C" interface, and create header file to wrap that interface in classes. Something like:
class WConfig {
public:
WConfig(): m(IDll->create()) {
}
// other member functions as interface stub
~WConfig() {
IDll->release(m);
}
private:
Config* m;
};
To share this object, you can use copy constructor (that copy the pointer and call to IDll->reference(m), for example) or any other approach.

Style consistency when subclassing from an external library in a new project?

Keeping a consistent style is important when adding to an existing project. But what about when subclassing heavily from a library in a new project when there are distinct differences between the project's and the library's standard?
I'm working on a project with a particular coding style, specifically when it comes to how classes and methods within those classes are named. One module of the project however, the UI, relies heavily on an external library and most of the classes in this module will overload this library. In this case, it's Qt, but it could be anything.
In such a situation, is it better to stick to the style used by the API or use the project's style for new functions? As an example, Qt uses camelCase for its function declarations whereas this project uses UpperCase. Consider something like this:
class MyNewWidget : public QWidget {
Q_OBJECT
public:
void setVisible(bool visible); // QWidget override
void SetNewFeature(std::string feature_key); // New function
bool visibility() const; // I know you can't override that, but bear with me
std::string GetNewFeature() const; // propertyName() vs GetPropertyName()
};
This feels along the same lines as subclassing from STL which uses lower_case. There are some good reasons in that case to follow convention in some instances at least, e.g. when typedef'ing iterator types or if you want your begin/end/swap functions to be usable by <algorithm> et al.
But I'm at a wall on this one.
I would strive to maintain a single style per class/file/module where possible. The difficulty comes when you're trying to think of the name of a method, and the less you can cause others to stop and think, the better. Of course, a good IDE/editor should correct your case.
Another option is to favor composition over inheritance. This would mean you'll write new methods using your projects style that delegate to the Qt methods internally. It will give you the added benefit of not being tied to the Qt API if that's at all a concern.

Handling metro event in native c++ class

I would like to handle a button clicked event in a native c++ class. I have tried creating a 'handler' object derived from Object to handle the event and then calling a c++ method. For example I tried the following code:
ref class GButtonHandler sealed : public Object
{
public:
void Button_Click(Object^ sender, RoutedEventArgs^ e)
{
}
GTextBlockHandler(GButtonImpl * pButtonImpl, Button ^ button)
{
button->Click += ref new RoutedEventHandler(this, &GTextBlockHandler::Button_Click);
}
};
Thinking that I could squirrel away the pButtonImpl pointer and then use it to call a native function in the Button_Clicked function. However on compiling this code, I get the error:
error C3986: '{ctor}': signature of public member contains native type 'GButtonImpl'
So it seems that it does not like me passing in native classes into an ref object. Is there a way to do this?
Note that I am completely new to developing Metro style apps, so bear with me!
Ok, it all makes sense to me now. For anyone else who is interested, the reason you cannot have WinRT Objects with public functions that have native C++ arguments is that these objects would then not be consumable by non C++ code. However, the (obvious?) solution is to make the constructor private and have the class that creates the Object declared as a 'friend' class (duh!). Then all is well, the compiler is happy, and I am happy.
Thanks to all who took the time to read this.
The correct answer is to use internal rather than public for the constructor. This tells the compiler that it will only be available in the current project, and won't be available to external projects (i.e. a library written in another language).

How to pass managed reference to unmanaged code in C++/CLI?

I'm using C++/CLI only to unit test unmanaged C++ code in VS2010. I switched the compiler to /clr and using the unmanaged code from a static library.
I have a simple int property in my test class.
I would like to pass that as a const int & to a function in native C++. But it can't compile and I've found out that, it's because you can't mix references like that.
What is the way to do it, I tried to following and it's working, but is there a nicer way?
[TestClass]
public ref class MyTestClass
{
private:
int _my_property;
public:
[TestMethod]
void MyTestMethod()
{
MyNativeClass c;
// c.SomeMethod(_my_property) this doesn't work
int i = _my__property;
c.SomeMethod(i) // this works
}
}
C++ references are really just syntactic sugare for pointers. A C++ pointer points to a specific point in memory, while CLI references can be freely moved around by the garbage collector. To pass a reference to an object in managed memory to unmanged code, you need to pin the pointer.
More info and sample in another SO question: Convert from C++/CLI pointer to native C++ pointer
Edit 2
I'm removing the additional information, since it is obviously wrong (thanks #Tergiver and #DeadMG for your comments). I'm also making the post community wiki, so feel free to add any additional correct information.

Resources