简体   繁体   English

按值传递结构,在C-> C ++回调函数(gcc 4.1)中损坏

[英]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). 我看到一种结构,当它按值传递给回调函数时,结构从C API到C ++(通过静态方法)损坏。

Library A: C-based API, built via gcc Library B: C++-based API, built via g++ 库A:通过gcc构建的基于C的API库B:通过g ++构建的基于C ++的API

Library A is built as a static lib, with -fPIC. 库A使用-fPIC构建为静态库。 Library B is built as a shared lib, linking Library A, also built with -fPIC. 库B是作为共享库构建的,它链接库A,也通过-fPIC构建。

Defined in Library A, is a struct: 在库A中定义的是一个结构:

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. C ++ API在类中定义了一个静态方法,并将其交给C API进行回调。 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. 当调用此回调时,简单类型的arg1,2,3使其完全正常,但是struct中的字段是垃圾,并且在每次执行时都会更改。

I've tried changing the C++ API's function to be a extern "C" static function as well, no luck there. 我尝试过将C ++ API的功能也更改为extern "C"静态功能,但没有运气。

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. 如果我在C API中存根一个C函数并调用它只是为了进行测试,则该结构将被复制而不会损坏。

The frustrating part? 令人沮丧的部分? This all works fine on MSVC8/9/10, gcc 4.4.x (32 and 64-bit) on Linux and QNX. 在MSVC8 / 9/10,Linux和QNX上的gcc 4.4.x(32位和64位)上,这些都可以正常工作。 Moving back a few years to gcc 4.1, this pops up. 回到几年前到gcc 4.1,这弹出。

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. C,C API具有ABI限制,无法修改。

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. 总体而言,该结构为16字节,因此它不会对我造成尖叫。

This appears to be related to optimization levels. 这似乎与优化级别有关。 Code was being built with -O0 and failing, now with -O1 it works. 代码是使用-O0生成的,但是失败了,现在使用-O1可以正常工作。 Not interested in digging any deeper! 没兴趣进一步挖掘!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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