Part 1 of 2
Pointers are often required to interface with C libraries when data needs to be passed into an existing API. This mechanism is not limited to "legacy" systems, modern examples include OpenGL, DirectX, and Win32.
below is an example from OpenGL:
glVertexPointer(int,float,int,float*) takes a float pointer as the first argument.
GLfloat vertices[] = {...}; // 24 of vertex coords
...
// activate and specify pointer to vertex array
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
// draw a cube
glDrawArrays(GL_QUADS, 0, 24);
// deactivate vertex arrays after drawing
glDisableClientState(GL_VERTEX_ARRAY);
instead of using an statically defined array it would be ok to do the following:
Glfloat *vertex = new GlFloat[24];
...
glVertexPointer(3, GL_FLOAT, 0, vertices);
...
delete [] vertex.
or if you want to use std::vector
std::vector<Glfloat> vertex;
vertex.resize(24);
...
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
...
Part 2 of 2
Pointers to objects and function pointers are useful in defining static member function that needs to operate on a specific instance of a class. This idiom appears in callback mechanisms.
class foo {
...
public:
static int s_callback0(void* obj){
return (foo*)(obj)->callback0();
}
int callback0(){
...
}
...
};
class callbackAPI {
public:
int setCallback(int(*fn)(void*),void* context){
m_fn(fn);
m_context(context);
}
void run (){
m_fn(m_context);
}
private:
int(*m_fn)(void*);
void *m_context;
};
main {
foo f;
callbackAPI cb;
cb.setCallback(foo::s_callback0,f);
cb.run();
}
If you have control of callbackAPI similar results could be achieved with inheritance and templates. The above examples demonstrates a way of working with a callbackAPI provided by a 3rd party when required to provide a function pointer.