Memory allocation and deallocation across dll boundaries

后端 未结 3 1396
Happy的楠姐
Happy的楠姐 2020-12-02 00:39

I understand that memory allocations made in one dll then subsequently free\'d in another can cause all sort of problems, especially regarding the CRT. These sorts of probl

3条回答
  •  死守一世寂寞
    2020-12-02 00:42

    At the moment we're working on a dll which exposes C++ functionality via a C interface (for the sake of C# being capable of using the said dll).

    for instance : the dll has a struct myStruct_s the interface exposes the following functions :

    interface.h

    #ifndef INTERFACE_TYPES_H
    # error Please include interace_types.h
    #endif
        myStruct_s * CreateTheStruct() { return new myStruct_s(); }
        void DestroyTheStruct(myStruct_s * the_struct) { delete the_struct; }
        void DoSomethingToTheStruct(myStruct_s * the_struct);
    

    interface_types.h

    #define INTERFACE_TYPES_H
    struct myStruct_s; // fwd declaration
    #endif
    

    interface.cpp

    #if defined(__CPPPLUS) || defined(__cplusplus) || defined (__CPLUSPLUS)
    #include
    // handle the .h's functions here
    #endif
    

    comeOutsideCppFile.cpp

    #include "interface_types.h"
    #include "interface.h"
    
    void main()
    {
        myStuct_s * x = CreateTheStruct;
        DoSomethingToTheStruct(x);
        DestroyTheStruct(x);
    }
    

    The above is a rough outline of how our stuff works, basically : Whatever the dll exposes needs to be : Created, Handled, Destroyed dll-side

    This code is not 100% accurate!!!

    Also, please keep in mind that if you're using a pure C++ dll, you probably need the same compiler with the same settings as the one used to build the dll.

提交回复
热议问题