Trouble understanding crash when class is returned by value from C++

Iain Buclaw ibuclaw at ubuntu.com
Mon Sep 3 09:38:24 PDT 2012


On 3 September 2012 16:52, Daniel Green <venix1 at gmail.com> wrote:
> My best guess, is the issue is related to the struct being 4 bytes.
> A similar segfault occurs if you attempt to access in a similar manner using
> c++.
>
> A 4 byte struct will fit into a single register making pointers
> unnecessary/slower and it's likely some part of the ABI has taken this into
> consideration and the compiler is optimizing access to this.
>
> However, I would imagine that such optimizations would not be allowed with
> C++ and so by using a class it requires a pointer type and not the optimized
> struct.
>
> The following returns the value of 4 when I inspect the variable refValue
> instead of the correct address and segfaults.
>
> http://codepad.org/eepFTfbX


Indeed,  C++ classes are always passed in memory by design.  Whereas
pointers could be passed in registers.  The difference between ABI
handling of void* and FileName* here matter a lot.  And this is one
reason why you need to ensure that function signatures match in both D
and C/C++ code.

extern "C"
FileName value_FileName(void* refVal)
{
    return *(FileName*)refVal;
}

By the way, why extern "C" when extern (C++) works just fine? :-)


Regards
-- 
Iain Buclaw

*(p < e ? p++ : p) = (c & 0x0f) + '0';


More information about the D.gnu mailing list