【问题标题】:Storing a pointer's address in an unsigned int in C将指针的地址存储在 C 中的无符号整数中
【发布时间】:2012-05-09 06:32:51
【问题描述】:

是否可以将指针转换为无符号整数,然后再将其转换回指针?我试图将指向结构的指针存储在 pthread_t 变量中,但我似乎无法让它工作。这是我的代码的一些 sn-ps(我正在创建一个用户级线程管理库)。当我尝试打印线程的 tid 时,它给了我一些很长的垃圾号码。

编辑:没关系,我得到了它的工作。

我变了

thread = (pthread_t) currentThread;

*thread = (pthread_t) currentThread;

认为这是愚蠢的事情。


测试程序:

pthread_t thread1;
pthread_t thread2;

pthread_create(&thread1, NULL, runner, NULL);
pthread_create(&thread2, NULL, runner, NULL);
pthread_join(&thread2, NULL);

我的图书馆:

typedef struct queueItem
{
    int tid;
    ucontext_t context;

    int caller;

    struct queueItem *joiningOn;
    struct queueItem *nextContext;
} queueItem;

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
    thread = (pthread_t) currentThread;
}

...

int pthread_join(pthread_t thread, void **retval)
{
    queueItem *t = (queueItem *) thread;

    if(runningContext->joiningOn != NULL) // Current thread is already waiting on another
        return EINVAL;
    if(t == NULL) // If thread to join on is invalid
        return 0;

    fprintf(stdout, "JOINEE: %d\n", t->tid); // Prints weird number

    runningContext->caller = JOIN;
    runningContext->joiningOn = t;
    swapcontext(&(runningContext->context), &scheduleContext);
}

【问题讨论】:

  • 我不明白——你在自己的库中定义了 pthread_create 吗?为什么要用该名称与通常的功能冲突??
  • 没关系,让它工作。编辑了我原来的帖子。

标签: c casting pthreads


【解决方案1】:

当然可以,如果您确保 unsigned int 与系统上的 void* 大小相同。

如果您的某些代码不起作用,请发布。

编辑:您应该阅读intptr_t,例如这里:Why / when to use `intptr_t` for type-casting in C?

【讨论】:

  • 相同或更大。 + 你忘了对齐。
  • 当然,如果 unsigned int 更大,我想没关系。至于对齐,您是否考虑过可能有问题的特定情况?
  • 具体 - 没有。但一般来说,不同的 POD 类型可能需要 CPU 架构具有不同的对齐要求。这不在 C 标准中,所以如果明天我在 Verilog 中编写我的 CPU,它的大小为 64 位的 unsigned int 并要求它按 16 对齐,然后制作一个 8 位指针,要求它在 8 上对齐,这可能会导致 foobar :) 士气 - 如果您不知道,请使用 memcpy。 + pthread_t 是不透明类型...
  • 当然,如果您关心可移植性,将字节从 int 复制到指针是有意义的。我认为 OP 还没有达到那种细化水平。 :) 无论如何 +1。
  • 我已经发布了我的一些代码。 pthread_t 类型(unsigned int)和 queueItem 指针的长度在我的机器上都是 4。
【解决方案2】:

没有。在许多系统上,指针类型大于 int 类型。如果你在使用 pthread_t 有问题,问一下,int 不是答案。

例如,在我的机器上,如下代码:

#include <stdio.h>

int main() {
        printf("unsigned int = %lu\n", sizeof(unsigned int));
        printf("pointer = %lu\n", sizeof(void*));
        return 0;
}

输出:

unsigned int = 4
pointer = 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多