简体   繁体   English

将指针的地址存储在C中的unsigned int中

[英]Storing a pointer's address in an unsigned int in C

Is it possible to cast a pointer to an unsigned int, then later cast it back to a pointer? 是否可以将指针强制转换为unsigned int,然后将其转换回指针? I'm trying to store the pointer to a struct in a pthread_t variable, but I can't seem to get it to work. 我正在尝试将指针存储到pthread_t变量中的结构,但我似乎无法让它工作。 Here's some snippets of my code (I'm creating a user-level thread management library). 这是我的代码的一些片段(我正在创建一个用户级线程管理库)。 When I try to print out the tid of the thread it gives me some long garbage number. 当我尝试打印出线程的tid时,它会给我一些很长的垃圾编号。

Edit: Never mind, I got it to work. 编辑:没关系,我让它工作。

I changed 我变了

thread = (pthread_t) currentThread;

to

*thread = (pthread_t) currentThread;

Figured it was something stupid like that. 认为这是愚蠢的事情。


Test program: 测试程序:

pthread_t thread1;
pthread_t thread2;

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

My library: 我的图书馆:

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);
}

No. On many systems pointer type is bigger than int type. 在许多系统上,指针类型大于int类型。 If you have a problem to use pthread_t, ask about it, int is not the answer. 如果您有使用pthread_t的问题,请询问它,int不是答案。

For example, on my machine, the following code: 例如,在我的机器上,以下代码:

#include <stdio.h>

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

outputs: 输出:

unsigned int = 4
pointer = 8

Sure it's possible, if you make sure your unsigned int is the same size as a void* on your system. 当然,如果你确定你的unsigned int与你系统上的void *相同,那么这是可能的。

If you have some code that's not working, post it. 如果您有一些不起作用的代码,请发布它。

Edit: You should read about intptr_t , eg here: Why / when to use `intptr_t` for type-casting in C? 编辑:您应该阅读有关intptr_t ,例如:这里为什么/何时使用`intptr_t`在C中进行类型转换?

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

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