开发者

C - Glib GINT_TO_POINTER portability

开发者 https://www.devze.com 2023-01-11 16:48 出处:网络
I\'m dealing with large numbers coming fr开发者_开发知识库om the hash table. I\'m wondering what would be a good way of adding them to a constant (100) taking into account portability. Glib\'s documen

I'm dealing with large numbers coming fr开发者_开发知识库om the hash table. I'm wondering what would be a good way of adding them to a constant (100) taking into account portability. Glib's documentation highlights that using GINT_TO_POINTER is not portable in any way. Any ideas would be appreciated!

gpointer v, old_key;
gint value; // ?

if(g_hash_table_lookup_extended(table, key, &old_key, &v)){
    value = GPOINTER_TO_INT(v); // ?
    value = value + 100;
}
g_hash_table_replace(table, g_strdup(key), GINT_TO_POINTER(value)); // ?


I am not familiar with gnome library, but from GNOME Documentation Library:

YOU MAY NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

The only thing not portable is to store pointers in integers. If you just:

  • Store integers in pointers. (not pointers in integer).
  • The integer does not not exceed 32 bits.

It shall be okay.


Rather than storing an integer inside a pointer, have the pointer point to an integer:

gpointer v, old_key;
int *int_v;
if(g_hash_table_lookup_extended(table, key, &old_key, &v)){
    int_v = (int *)v;
    int new_value = *int_v + 100;
    int_v = g_malloc(sizeof(int));
    *int_v = new_value;
}
g_hash_table_replace(table, g_strdup(key), int_v);

For a new value, use g_malloc:

// ...
int *value = g_malloc(sizeof(int));
// ...
g_hash_table_insert(table, key, value);

To ensure keys and values are destroyed properly, pass destructor functions like g_free to g_hash_table_new_full.

0

精彩评论

暂无评论...
验证码 换一张
取 消