简体   繁体   English

更改作为 void* function 参数传递的变量的地址

[英]Change the address of a variable passed as a void* function parameter

I have a callback function void string_cb(char* data, size_t size, void* str) which uses a prototype void callback_decl (char* data, size_t size, void* ret_val) where the last parameter is a return value.我有一个回调 function void string_cb(char* data, size_t size, void* str)它使用原型void callback_decl (char* data, size_t size, void* ret_val) ,其中最后一个参数是返回值。 Because my callback needs to allocate a memory for a string with malloc() , I need to change the address of the void* str to allocated memory block.因为我的回调需要为带有malloc()的字符串分配 memory ,所以我需要将void* str的地址更改为分配的 memory 块。 Is it possible to assign a new address to str without changing the callback prototype?是否可以在不更改回调原型的情况下为 str 分配新地址?

Yes you can... but not with your string_cb declaration.是的,你可以......但不是你的string_cb声明。 If you want to be able to return the address of a newly allocated array, you need a char ** as the last parameter:如果你希望能够返回一个新分配的数组的地址,你需要一个char **作为最后一个参数:

void slbin_handler_nstring(char* data, size_t data_size, void* ret_ptr) {
    char** ptr = (char **) ret_ptr;
    *ptr = malloc(data_size);
    if (!(*ptr)) return;
    memcpy(*ptr, data, data_size);
}

If should be called that way:如果应该这样调用:

char *ptr;
slbin_handler_nstring(data, data_size, &ptr) ;

With the signature void callback_decl (char* data, size_t size, void* ret_val) , the caller is solely responsible for providing allocated memory.使用签名void callback_decl (char* data, size_t size, void* ret_val) ,调用者全权负责提供分配的 memory。 It is not possible for the invoked callback to allocate memory internally.调用的回调不可能在内部分配 memory。

If you think about it for a moment, that's actually to prefer, as the caller knows a lot better where the memory should be allocated (heap or stack), and has full control over the entire life time of the string.如果您考虑一下,这实际上是更喜欢的,因为调用者更清楚应该在哪里分配 memory(堆或堆栈),并且可以完全控制字符串的整个生命周期。

Usually this pattern is combined with a special value for ret_val which indicates provided bufferis too small so that the caller can issue the callback again, but with a larger buffer.通常这种模式与ret_val的特殊值结合使用,表示提供的缓冲区太小,以至于调用者可以再次发出回调,但缓冲区更大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM