I working with a library where I need to send a pointer to an object to a function.. the problem is that I need to change what this pointer points to in the function itself, and I don't really know how I can overcome this problem since pointers are passed-as-value..
struct.cpp
struct MyStruct {
Node* previous;
...
};
main.cpp
int main(...) {
MyStruct* m = new MyStruct;
m->previous = NULL;
...
while (traversing) {
library_function((AFUNPTR) myFunction, (void*) m->previous);
}
function.cpp
void myFunction(void* node_from_lib, void* point_to_previous) {
Node* current = (Node*) node_from_lib;
Node* previous = (Node*) point_to_previous;
if (previous != NULL) {
...
}
previous = current;
}
My problem is that I need to traverse through all the nodes, but this way previous will be sent into myFunction
pointing to NULL
all the time.. I've tried to use Node** previous
and assign the "new" previous like *previous = current;
but I'm still getting a seg-fault.
The library I'm using is Intel-PIN and I'm trying to instrument an instruction and chain them into a graph, although I've stripped away everything PIN from the example since I think this is a general c++ problem?
Here is my attempt with a pointer to a pointer...
struct.cpp
struct MyStruct {
Node** previous;
...
};
main.cpp
int main(...) {
MyStruct* m = new MyStruct;
*(m->previous) = NULL;
...
while (traversing) {
library_function((AFUNPTR) myFunction, (void*) m->previous);
}
function.cpp
void myFunction(void* node_from_lib, void** point_to_previous) {
Node* current = (Node*) node_from_lib;
Node** previous = (Node**) point_to_previous;
if ((*previous) != NULL) {
(*previous)->memberFunc();
...
}
*previous = current;
}
C:
int main(...) {
MyStruct* m = new MyStruct;
m->previous = NULL;
...
while (traversing) {
library_function((AFUNPTR) myFunction, &m->previous);
}
here, pass the m->previous
via pointer (the pointer is then of type Node**
, that can be reinterpreted to void*
and back without losing anything. The function expects void*
.)
function.cpp
void myFunction(void* node_from_lib, void* point_to_previous) {
Node* current = (Node*) node_from_lib;
Node* previous = * ((Node**)point_to_previous); // cast for reading - assume point_to_previous is pointer to pointer, and retrieve the pointer
if (previous != NULL) {
...
}
previous = current;
*((Node**)point_to_previous) = previous; // assume, point_to_previous is pointer to pointer, and change the pointer
}
Here, you can cast back the void*
to Node**
.
Here, you pass the pointer to node pointer ( Node**
) as a second parameter. It is reinterpreted as void*
, but it is just semantic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.