简体   繁体   中英

Struct passed by value, corrupted during C -> C++ callback function (gcc 4.1)

The scenario is this. I am seeing a struct get corrupted when it is passed by value into a callback function, from a C API to a C++ one (via a static method).

Library A: C-based API, built via gcc Library B: C++-based API, built via g++

Library A is built as a static lib, with -fPIC. Library B is built as a shared lib, linking Library A, also built with -fPIC.

Defined in Library A, is a struct:

typedef struct doomed_struct
{
    uint32_t field1;
    uint32_t field2;
    CHILD_STRUCT1 field3;
    CHILD_STRUCT2 field3;
} DOOMED_STRUCT;

and a callback function:

typedef void (_CALLBACK_FUNC *FUNCTION)(uint32_t arg1, uint8_t arg2,
    uint8_t arg3, DOOMED_STRUCT arg4);

The C++ API has a static method defined in a class, and hands this to the C API for a callback. When this callback gets invoked, the simple typed arg1,2,3 make it over just fine, but the fields in the struct are garbage, and change on every execution.

I've tried changing the C++ API's function to be a extern "C" static function as well, no luck there.

If I stub out a C function in the C API and call it just to test, the struct is copied over just fine without corruption.

The frustrating part? This all works fine on MSVC8/9/10, gcc 4.4.x (32 and 64-bit) on Linux and QNX. Moving back a few years to gcc 4.1, this pops up.

If I change the callback function to pass the struct via a pointer instead of copy, it works fine! Alas, the C API has ABI restrictions, and can't be modified.

It smells like some kind of calling convention or struct layout issue, but I have no clue what knobs to turn for something like this. Overall the struct is 16 bytes, so it doesn't scream stack issue to me.

This appears to be related to optimization levels. Code was being built with -O0 and failing, now with -O1 it works. Not interested in digging any deeper!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM