Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning C++ objects from Windows DLL

Tags:

c++

windows

dll

Due to how Microsoft implements the heap in their non-DLL versions of the runtime, returning a C++ object from a DLL can cause problems:

// dll.h
DLL_EXPORT std::string somefunc();

and:

// app.c - not part of DLL but in the main executable
void doit()
{
    std::string str(somefunc());
}

The above code runs fine provided both the DLL and the EXE are built with the Multi-threaded DLL runtime library.

But if the DLL and EXE are built without the DLL runtime library (either the single or multi-threaded versions), the code above fails (with a debug runtime, the code aborts immediately due to the assertion _CrtIsValidHeapPointer(pUserData) failing; with a non-debug runtime the heap gets corrupted and the program eventually fails elsewhere).

Two questions:

  1. Is there a way to solve this other then requiring that all code use the DLL runtime?
  2. For people who distribute their libraries to third parties, how do you handle this? Do you not use C++ objects in your API? Do you require users of your library to use the DLL runtime? Something else?
like image 354
R Samuel Klatchko Avatar asked Nov 05 '22 14:11

R Samuel Klatchko


1 Answers

Is there a way to solve this other then requiring that all code use the DLL runtime?

Not that I know of.

For people who distribute their libraries to third parties, how do you handle this? Do you not use C++ objects in your API? Do you require users of your library to use the DLL runtime? Something else?

In the past I distributed an SDK w/ dlls but it was COM based. With COM all the marshalling of parameters and IPC is done for you automatically. Users can also integrate in with any language that way.

like image 125
Brian R. Bondy Avatar answered Nov 12 '22 16:11

Brian R. Bondy