Passing data between dll boundaries in c++ Safely

Viewed 2049

Let there be a structure

struct MyDataStructure
{
    int a;
    int b;
    string c;
};

Let there be a function in the interface exposed by a dll.

class IDllInterface
{
    public:
       void getData(MyDataStructure&) = 0;
};

From a client exe which loads the dll, would the following code be safe?

...
IDllInterface* dll = DllFactory::getInterface(); // Imagine this exists
MyDataStructure data;
dll->getData(data);
...

Assume, of course, that MyDataStructure is known to both the client and the dll. Also according to what I understand, as the code is compiled separately for the dll and exe, the MyDataStructure could be different for difference compilers/compiler versions. Is my understanding correct.

If so, how can you pass data between the dll boundaries safely when working with different compilers/compiler versions.

3 Answers

Using JSON for communication.

I think I have found an easier way to do it hence answering my own question. As suggested in the answer by @Greg, one has to make sure that the data representation follows a protocol e.g. network protocol. This makes sure that the object representation between different binary components (exe and dll here) becomes irrelevant. If we think about it again this is the same problem that JSON solves by defining a simple object representation protocol.

So a simple yet powerful solution according to me would be to construct a JSON object from your object in the exe, serialise it, pass it across the dll boundary as bytes and deserialise it in the dll. The only agreement between the dll and exe would be that both use the same string encoding (e.g. UTF-8).

https://en.wikibooks.org/wiki/JsonCpp

One can use the above Jsoncpp library. The strings are encoded by UTF-8 by default in Jsoncpp library so that it convenient as well :-)

Related