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
    }
}
2
  • You also need to be certain that you are actually allocating memory for var. Commented Mar 3, 2016 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. Commented Mar 4, 2016 at 6:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@IlDivinCodino OK, good, then. As a non-native English speaker, sometimes I have trouble understanding other dialects.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.