Reputation: 11
I have searched SO and Google for 3 hours and cannot find the resolution for what I am seeing.
I have a .cpp vector support program which provides c++ functionality to a larger c program. I already have a queue .cpp working fine, the queue pushes and pops copies of values/elements it is passed back and forth, so the exporting of functions and build is working.
A problem occurs when trying to copy and return the value of an element in a vector.
usage in .c file
vector_type *temp;
...
_Vector_At(VectorHandle, i, temp);
if(temp == NULL)
printf("null\n");
printf("Returned %x\n", temp);
.cpp:
typedef struct
{
std::vector<vectory_type*> q;
pthread_mutex_t mutex;
} VECTOR;
...
int _Vector_At(VECTOR_HANDLE handle, short index, vectory_type *ptr)
{
VECTOR *q = (VECTOR *)handle;
if (NULL == q)
{
return(-1);
}
ptr = q->q[index];
printf("Test %x\n", ptr);
return(0);
}
Console output is
Test <expected memory address>
null
Returned 0
I am able query values of what is pointed to by ptr only inside the accessor function. Somehow the value of ptr is being erased when it is returned from the .cpp program to the .c program. But this does not make any sense that std::queue works fine with pushing and popping values in the exact same fashion.
Anyone have any ideas? Thanks.
Upvotes: 1
Views: 137
Reputation: 151
In the c code you are passing in the vector_type *temp
to the function _Vector_At
. The _Vector_At
function is making a local copy of the pointer as ptr
and using that to modify the value, but it is not returning that value as you want to. This is because it is a local variable and it's lifetime comes to an end at the end of the _Vector_At
function.
To solve this you can either pass the pointer as a reference or pointer pointer:
_Vector_At(VECTOR_HANDLE handle, short index, vectory_type* &ptr)
or
_Vector_At(VECTOR_HANDLE handle, short index, vectory_type** ptr)
Upvotes: 2