user1589684
user1589684

Reputation: 45

How to pass a struct from C++ application to a C++ Win32 DLL?

How to pass a struct from C++ application to a C++ Win32 DLL?

Would you please give me an example?

Upvotes: 3

Views: 879

Answers (2)

Mr.C64
Mr.C64

Reputation: 43044

How is your struct defined? Is it a POD? Is it a simple C struct? Or is it a struct that has members that are instances of STL classes?

If the struct is a "pure C" struct, then you can simply pass it to the DLL.

But if the struct has STL classes as data members, then you must be sure that both the .EXE and the .DLL use dynamic linking to CRT, and are built with the same version of Visual C++ compiler and same flavor of the CRT (e.g. you can't pass STL classes at the boundary if you have a debug-build .EXE and a release-build .DLL, because the implementations of the STL containers change from debug to release builds; and you can't pass STL classes at the boundary if you have an .EXE built e.g. with VC10 and a .DLL built with VC9).

Moreover, you may want to read this interesting article on CodeProject: "HowTo: Export C++ classes from a DLL".

Upvotes: 1

6502
6502

Reputation: 114599

You can pass a pointer because the DLL in windows are in the same address space as the program.

Note however that the DLL interface stops there and you (normally) do not have a shared memory management and you cannot in general pass for example an std::vector and expect the DLL to be able to push_back new elements. The reason is that the DLL has in general its own memory manager and heap, separated from the one of the caller (after all DLL can be called from any language, not necessarily C++).

Even if it may be surprising passing an std::map and having the DLL and only just reading it still may not work, because some containers in the standard library depends on "sentinels" and and these could be duplicated for the DLL too.

In the above I used the term "in general" because the DLL may have some trickery to be able to share the memory management with the main process. For example microsoft MFC was designed to work properly around these DLL barriers since VC6 (but NOT the standard library!).

You must also be sure that DLL and the main program are compiled with the exact same compiler and compiling options because otherwise even plain structures may have a different memory layout.

Upvotes: 4

Related Questions