Search code examples
c#c++visual-c++interop

What is the memory layout of std::optional ? (C# interop with std::optional)


Using C# interop I need to call a function in a 3rd party C++ library. The C++ function expects a std::optional argument:

void FunctionToCall(std::optional<wchar_t const*> arg)

I guess I'll have to model std::optional as a struct containing a bool and a pointer. But I didn't find any information about the memory layout of std::optional. The memory layout might even be compiler-specific. So, just in case it makes a difference: It looks like the C++ library was written using Microsoft VC++.

So my question is: What is the memory layout of std::optional in VC++? How to do interop properly in this case?


Solution

  • Using clang's pahole tool, this is what comes out

    
    class optional<int> : _Optional_base<int, true, true> {
    public:
    };
    
    struct _Optional_base<int, true, true> : _Optional_base_impl<int, std::_Optional_base<int, true, true> > {
        struct _Optional_payload<int, true, true, true> _M_payload; /*     0     8 */
    };
    
    class _Optional_base_impl<int, std::_Optional_base<int, true, true> > {
    protected:
    };
    
    struct _Optional_payload<int, true, true, true> : _Optional_payload_base<int> {
    };
    
    struct _Optional_payload_base<int> {
        union _Storage<int, true>  _M_payload;           /*     0     4 */
        bool                       _M_engaged;           /*     4     1 */
    };
    
    union _Storage<int, true> {
        struct _Empty_byte         _M_empty;           /*     0     0 */
        int                        _M_value;           /*     0     4 */
    };
    
    struct _Empty_byte {
    };
    
    

    Godbolt: https://godbolt.org/z/r4KTfYKoW

    In the end this is equivalent to

    class optional<int> { 
        int value;
        bool used;
    };