Jeegar Patel
Jeegar Patel

Reputation: 27210

Need help in understanding this code

There some code in one gstreamer-plugin:

static GstFlowReturn
gst_ebml_peek_id_full (GstEbmlRead * ebml, guint32 * id, guint64 * length,
    guint * prefix)
{
  GstFlowReturn ret;

  ret = gst_ebml_peek_id_length (id, length, prefix,
      (GstPeekData) gst_ebml_read_peek, (gpointer) gst_ebml_read_br (ebml),
      ebml->el, gst_ebml_read_get_pos (ebml));
  if (ret != GST_FLOW_OK)
    return ret;

  GST_LOG_OBJECT (ebml->el, "id 0x%x at offset 0x%" G_GINT64_MODIFIER "x"
      " of length %" G_GUINT64_FORMAT ", prefix %d", *id,
      gst_ebml_read_get_pos (ebml), *length, *prefix);

Now see the 4:th argument to gst_ebml_peek_id_length () is

(GstPeekData) gst_ebml_read_peek

where gst_ebml_read_peek is another function whose definition is:

static const guint8 *
gst_ebml_read_peek (GstByteReader * br, guint peek)
{
  const guint8 *data = NULL;

  if (G_LIKELY (gst_byte_reader_peek_data (br, peek, &data)))
    return data;
  else
    return NULL;
}

Now I want to ask you is: gst_ebml_read_peek has two input argument in definition, so how can it be called (in the upper code) without arguments?

Edit: You can find this code at http://gstreamer.freedesktop.org/data/coverage/lcov/gst-plugins-good/gst/matroska/ebml-read.c.gcov.html

From around line 194.

Upvotes: 2

Views: 261

Answers (3)

spats
spats

Reputation: 853

Argument passed to gst_ebml_peek_id_full() is function pointer of gst_ebml_read_peek() or in other terms its just passing the handle of the function so that gst_ebml_peek_id_full() can call passed in function with correct parameter.

Gives flexibility of passing your own/different implementation of function which implements same prototype of gst_ebml_read_peek().

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

Here is a simpler example doing a similar thing:

#include <stdio.h>

typedef int (*binaryop)(int, int);

static int add(int a, int b) {
  return a + b;
}

static int mul(int a, int b) {
  return a * b;
}

static void print_result(binaryop op, int a, int b) {
  printf("%d\n", op(a, b));
}

int main() {
  print_result(add, 2, 3);
  print_result(mul, 5, 7);
  return 0;
}

The print_result function takes another function as a parameter, which it then calls. When you just write add without the parentheses, the function is not yet called. It is only called in a function call expression, and that looks like this: function_name(arguments).

Upvotes: 3

cnicutar
cnicutar

Reputation: 182639

Because it's a function pointer. The function is not actually called at that point, it's just passed to gst_ebml_peek_id_length (which will likely call it later with the correct arguments).

Upvotes: 8

Related Questions