Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I share variables between C and C++ code?

I'm working on a C++ project that implements C code and I'm stuck on a segmentation fault. The segfault occures when I try to access a global C variable in my C++ code.

Overview of the code:
I have a single c file called video_stage.c with the following code snippet:

#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);
}

This function is periodically called by other C code and updates the pixbuf_data pointer witch points to an RGB videoframe.

It's header file 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

The header file contains the extern declaration of the pixbuf_data pointer.

And here the cpp file: 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

}

When the function in the cpp file is called (by other cpp code), a segfault occures at the cout instruction that prints x.

When I do a printf of the first element of the buffer in the c file, I get what I expect.

I'm sure it has something to do with the mixing of c and c++ code, but according to my research I've done the stuff to make both c and c++ code compatible here.

like image 538
martin Avatar asked Oct 15 '25 02:10

martin


1 Answers

In C++ code pixbuf_data defined in a C source must be declared with C linkage:

extern "C" uint8_t*  pixbuf_data;

Without extern "C" the C++ code must not link, unless there is another (duplicate) definition of pixbuf_data with C++ linkage.

like image 180
Maxim Egorushkin Avatar answered Oct 17 '25 18:10

Maxim Egorushkin