使用指针到指针函数参数从库中检索值(由库API提供)

时间:2014-09-04 16:32:10

标签: c function-pointers protocol-buffers

我目前指的是以下示例 http://code.google.com/p/nanopb/source/browse/tests/callbacks/decode_callbacks.c#10

我修改了以下函数 - 因为不是使用' ** arg'而是将值传递给函数。我想使用' ** arg'来检索函数中获得的值。

bool print_int32(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
    return false;
        *arg = (void*) value; // This is 42

    printf("The value = %ld, *arg = %ld, arg = %ld\n", (long)value, (long)*arg, (long)arg); 
    return true;
}

(long)*arg现在 42 (long)arg拥有另一个值' -1234567890' 。 现在,在main函数中我更改了代码如下。

testmessage.submsg.int32value.funcs.decode = &print_int32;
long int32_dec = (long) &testmessage.submsg.int32value.arg; 
//long int32_dec = *(long*) testmessage.submsg.int32value.arg; //This seems to makes no difference
//long int32_dec = (long) testmessage.submsg.int32value.arg; //This seems to makes no difference

int32_dec值与我在(long)arg中看到的值相同(在我们的示例中' -1234567890' )。这不是我想要的。相反,我想得到 42 (在我们的示例中)代码中是否需要更改以获取 42 (在我们的示例中)?

更新[已解决] 感谢 jpa 确认我的指针概念和语法(一时间我以为我疯了)。核心问题是我在错误地放置代码片段时显然是愚蠢的。

//This is wrong
long int32_dec = (long) testmessage.submsg.int32value.arg;
if (!pb_decode(&stream, TestMessage_fields, &testmessage))
    return 1;

原因是它获得的值不是由解码例程更新的,与 42 不同(在我们的示例中)。

//This is correct
if (!pb_decode(&stream, TestMessage_fields, &testmessage))
    return 1;
long int32_dec = (long) testmessage.submsg.int32value.arg;

1 个答案:

答案 0 :(得分:1)

你只有一个&标志太多了。 这应该有效:

long int32_dec = (long)testmessage.submsg.int32value.arg;

arg视为一个可用于传递任何内容的自由字段,就像您正在做的那样。为了在回调中写入它,您需要使用*arg,就像您正在做的那样。但是,在回调之外,您可以直接阅读,而不需要&*