cast a C char array - offset ?

irtcupc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 2 05:23:23 PST 2015


On Monday, 2 February 2015 at 12:42:24 UTC, FG wrote:
> On 2015-02-02 at 13:16, irtcupc wrote:
>> The manual section about interfacing from c states that 
>> "type[]" is inter-compatible from C to D,
>>
>> however, I face this strange case:
>>
>> - C declaration:
>> char identifier[64];
>>
>> - D declaration:
>> char[64] identifier;
>>
>> - the result is only correct if i slice by (- pointer size):
>> char[64] fromC(char[64] * thing)
>> {
>>     const offs = size_t.sizeof;
>>     return thing[-offs.sizeof .. $-offs];
>> }
>>
>> Is this correct ?
>
>
> So you have to shift the whole array right by 4 or 8 bytes? 
> Strange.
> Looks like an alignment issue. Is identifier part of a bigger 
> structure?

Yes:

C struct:

#pragma pack(1)
typedef struct _Disasm {
    UIntPtr EIP;
    UInt64 VirtualAddr;
    UInt32 SecurityBlock;
    char CompleteInstr[INSTRUCT_LENGTH];
    UInt32 Archi;
    UInt64 Options;
    INSTRTYPE Instruction;
    ARGTYPE Argument1;
    ARGTYPE Argument2;
    ARGTYPE Argument3;
    PREFIXINFO Prefix;
    InternalDatas Reserved_;
} DISASM, *PDISASM, *LPDISASM;
#pragma pack()

D struct:

align(1)
struct _Disasm {
    void * EIP;
    ulong VirtualAddr;
    uint SecurityBlock;
    char [INSTRUCT_LENGTH] CompleteInstr;
    uint Archi;
    ulong Options;
    INSTRTYPE Instruction;
    ARGTYPE Argument1;
    ARGTYPE Argument2;
    ARGTYPE Argument3;
    PREFIXINFO Prefix;
    uint Reserved_[40];
}

my current understanding is that:
- C: char CompleteInstr[INSTRUCT_LENGTH] is actually a raw chunk
- D: defining the member as char[INSTRUCT_LENGTH] is an error
- the first member of a D array is the .length
- first char actually stands where .length uses to be, which 
explains the shift.
- I cant use fromStringz because it's not a null terminated string



More information about the Digitalmars-d-learn mailing list