我正在开发一个实现 C 代码的 C++ 项目,但遇到了段错误。当我尝试访问我的 C++ 代码中的全局 C 变量时,会发生段错误。
代码概览:
我有一个名为 video_stage.c 的 c 文件,其中包含以下代码片段:
#include "video_stage.h"
uint8_t* pixbuf_data = NULL; //pointer to video buffer
vp_os_mutex_t video_update_lock = PTHREAD_MUTEX_INITIALIZER;
C_RESULT output_gtk_stage_transform( void *cfg, vp_api_io_data_t *in, vp_api_io_data_t *out)
{
vp_os_mutex_lock(&video_update_lock);
/* Get a reference to the last decoded picture */
pixbuf_data = (uint8_t*)in->buffers[0];
vp_os_mutex_unlock(&video_update_lock);
return (SUCCESS);
}
此函数由其他 C 代码定期调用,并将指向 RGB 视频帧的 pixbuf_data 指针更新。
是头文件video_stage.h:
#ifndef _IHM_STAGES_O_GTK_H
#define _IHM_STAGES_O_GTK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <config.h>
#include <VP_Api/vp_api_thread_helper.h>
#include <VP_Api/vp_api.h> //hier zit vp_os_mutex in geinclude
PROTO_THREAD_ROUTINE(video_stage, data);
#ifdef __cplusplus
}
#endif
extern uint8_t* pixbuf_data;
extern vp_os_mutex_t video_update_lock;
#endif // _IHM_STAGES_O_GTK_H
头文件包含了 pixbuf_data 指针的外部声明。
这里是 cpp 文件:device.cc:
#include <iostream>
#include "video_stage.h"
int ardrone_update(ardrone_t *d)
{
uint8_t x;
x = pixbuf_data[0]; //no problem here, this is executed
std::cout << 5 << std::endl; //this is executed too
std::cout << x << std::endl; //segfault occures here
}
当调用 cpp 文件中的函数(由其他 cpp 代码)时,在打印 x 的 cout 指令处发生段错误。
当我对 c 文件中缓冲区的第一个元素执行 printf 时,我得到了我期望的结果。
我确信它与 c 和 c++ 代码的混合有关,但根据我的研究,我已经做了一些事情来使 c 和 c++ 代码在这里兼容。
最佳答案
在 C++ 代码中 pixbuf_data
在 C 源代码中定义必须使用 C 链接声明:
extern "C" uint8_t* pixbuf_data;
如果没有 extern "C"
,C++ 代码不能链接,除非有另一个(重复的)pixbuf_data
定义与 C++ 链接。
关于c++ - 如何在 C 和 C++ 代码之间共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656239/