[英]Crash when calling C++ function from C
I have a C++ library function which I am calling from a C function. 我有一个从C函数调用的C ++库函数。 The call passes in a C data-structure that is accessed by the C++ code.
该调用传入一个由C ++代码访问的C数据结构。 My program crashes in the C++ code when accessing the C data-structure.
访问C数据结构时,我的程序在C ++代码中崩溃。 I've followed all the instructions in C++ faq related to mixing C-to-C++.
我遵循了C ++常见问题解答中与C-to-C ++混合相关的所有说明。
The crash happens on a centos7 machine. 崩溃发生在centos7机器上。 Running the same code in debug mode does not result in a crash.
在调试模式下运行相同的代码不会导致崩溃。 The same code running on Ubuntu (16.04) does not result in a crash.
在Ubuntu(16.04)上运行的相同代码不会导致崩溃。 Here's the GDB analysis of the crash.
这是GDB对崩溃的分析。
(gdb) frame 5
#5 0x00007fc28e79226e in ngx_http_setup_handler (r=0x2469040)
at /opt/platform/nginx-noname-module.c:201
201 return ModProcessGetApi(r);
(gdb) p r->unparsed_uri
$1 = {len = 15, data = 0x24572c4 "/__xx/stats/all HTTP/1.1\r\nUser-Agent"}
(gdb) down
#4 0x00007fc28e7945b4 in ModProcessGetApi (r=r@entry=0x2469040)
at /opt/platform/nginx-body-handler.cc:274
274 ss_rval_t rv = ProcessGetRequest(r, data, &dsize);
(gdb) p r->unparsed_uri
$2 = {len = 38105792, data = 0xf <Address 0xf out of bounds>}
(gdb)
As soon as the execution enters the C++ code, the C data structure shows address out of bounds. 一旦执行输入C ++代码,C数据结构就会显示地址超出范围。 Here's is the glue code for c-to-c++ functions.
这是c-to-c ++函数的粘合代码。
#if __cplusplus
extern "C" {
#endif
#include <nginx.h>
#include <ngx_core.h>
#include <ngx_log.h>
#include <ngx_http.h>
ngx_int_t ModPostRequestBodyHandler(ngx_http_request_t *r);
ngx_int_t ModProcessGetApi(ngx_http_request_t* r);
#if __cplusplus
}
#endif
I would appreciate it if someone can shed some light on this. 如果有人可以对此有所阐明,我将不胜感激。 Are there any compiler options I need to use when mixing C and C++ code so that the C++ code can access the C data-structure properly?
混合C和C ++代码时是否需要使用任何编译器选项,以便C ++代码可以正确访问C数据结构? Here's the OS and compiler info:
这是操作系统和编译器信息:
Centos Version: Crash happens Centos版本:发生崩溃
OS: Centos 7, C++: g++ 4.8.5 操作系统:Centos 7,C ++:g ++ 4.8.5
Ubuntu Versions: Crash does not happen. Ubuntu版本:不会发生崩溃。
OS: Ubuntu 16.04, C++: g++ 5.4.0 操作系统:Ubuntu 16.04,C ++:g ++ 5.4.0
Not sure if it matters but I am running my app in a docker container on both OSes. 不确定是否重要,但是我正在两个操作系统的docker容器中运行我的应用程序。
It turns out my c++ and C libraries were getting compiled with different #defines, as a result, the C data-structure was different in both the libraries. 事实证明,我的c ++和C库正在使用不同的#defines进行编译,结果,两个库中的C数据结构均不同。 This results in misaligned access on the c++ side.
这会导致c ++方面的访问未对齐。 This problem could have happened in two c libraries as well.
这个问题也可能在两个c库中发生。
Thanks to all who responded. 感谢所有回应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.