2

I have a huge C Project. And now i needed a C++ function to fill some variables.

With declaring the function as extern "C", it was no problem, to call the function from the C Project.

The Problem is, that i need to pass a pointer to the C++ function, and in the function, i want to assign a value to the pointer. But exactly at this point, the program crashes with an "Segmentation fault".

Is there a way to make this work? Or is it impossible to work with pointers in this way between C and C++?


Calling the function as thread in C:

 Restwo = pthread_create(&num, NULL, (void *) function, &var);

Header

 #ifdef __cplusplus
extern "C"
{  // Dies sorgt dafür, dass der Header sowohl in C als auch in C++ funktioniert
#endif

    int function(int *pITS);

#ifdef __cplusplus
}
#endif

C++ Function

extern "C" {
    int getNewLsaSignals(int *var) {
        printf("Successfully started\n"); //works
        var = 19; //doesn't work
        //insert some c++ code here
    }
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Trikolix
  • 145
  • 4
  • You also need to be certain that you are actually allocating memory for `var`. – Cody Gray - on strike Mar 03 '16 at 15:14
  • In reality the variable is a complex struct, which is already filled with data. In the extern C++ function i just want to change these values. So there is already memory allocated for var. – Trikolix Mar 04 '16 at 06:43

1 Answers1

4

i want to assign a value to the pointer.

In that case, you need to change

 var = 19;

to

 *var = 19;

because, most likely, var = 19; makes the pointer to point to memory location that is inaccessible from your application, so any subsequent de-reference of that pointer will invoke undefined behavior.

Also, it's almost always safe to check the NULLity of the incoming pointer before directly de-referencing it.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • @IlDivinCodino OK, good, then. As a non-native English speaker, sometimes I have trouble understanding other dialects. – Sourav Ghosh Mar 03 '16 at 15:09
  • At first thanks for the answer, but If i use *var = 19; the compiler says: error: invalid type argument of unary ‘*’. If I code the same example like above in C code var = 19; works perfectly. But i need to do this in C++, and there it throes segmantation fail. – Trikolix Mar 04 '16 at 06:41
  • 1
    It does not work perfectly in C, either. It just compiles. It will bomb at run-time. Assigning a literal to a pointer is almost always a mistake. – Cody Gray - on strike Mar 04 '16 at 07:31