bratao
bratao

Reputation: 2080

How to Return a vector in a DLL?

I developing a plugin system to my Application. My software is written in MFC/c++

I Choose import the functions from a DLL. But i facing a problem. I had written using the std library, but SO showed my that "There is a danger when passing anything into and out of a DLL if it's based on a template"

So i started to rewrite it. But now i cannot found a good solution. This dll will parse the Youtube and return the results in a struct like this:

struct VideoInfo{
wchar_t* strName;
wchar_t* strURL;
int iDuration;
float fRate;
};

But will be 50 of those, in my previous code i just returned a std::vector<VideoInfo*> *vecVideos; but how can i do that in a safe way ?

Upvotes: 2

Views: 2408

Answers (2)

Hans Passant
Hans Passant

Reputation: 942348

It is only unsafe to return C++ objects when the DLL and the EXE were not built with the same project configuration, built with /MT instead of /MD or built with different versions of the runtime library. In many cases this is not a practical problem, ymmv.

The safe way is to avoid requiring the EXE to release memory that was allocated from the heap by the DLL. Or the other way around. You'll need to change your structure for starters, can't have wchar_t*. You'd write your exported function to take a VideoInfo* so that the caller can pass a buffer that the function fills in.

But reiterating, as long as there's no danger that the DLL is going to get obsolete then you won't have trouble with std::vector nor std::wstring.

Upvotes: 1

Mike Bailey
Mike Bailey

Reputation: 12817

Instead of returning a vector, you can create a linked list and return that.

No need to worry about incompatibility, and it's simple to use:

struct Node
{
    VideoInfo vi;
    Node *Next;
};

When you're building your list of videos, just do the following:

Node *ptr = new Node();
ptr->vi = MyVideoInfo; // Assumes MyVideoInfo is the new video
ptr->Next = current;
current = ptr; // Assuming current is our current linked list

You could even use this in c, since you'd just need to wrap it in an extern "C" {} and add typedef to the front of your declaration of the node.

Upvotes: 2

Related Questions