C pointers treated in python

Asked

Viewed 2,251 times

1

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

int main()
{
    setlocale(LC_ALL,"");

    int *x,valor,y;
    valor = 35;
    x = &valor;
    y = *x;

    printf("o endereço da variavel valor: %p\n", &valor);
    printf("endereço da variavel ponteiro x: %p\n", &x);
    printf("conteudo da variavel apontada por x: %d\n", x);
    printf("conteudo da variavel comum y: %d\n", y);    
}

I wish to make this code run within a program on python. How do I do? I’m starting to python but I want to work with pointers by merging the languages, because until then I haven’t found how to do this only with python.

1 answer

1

Roughly, within the standard Python data model, pointers can be viewed as an analogy to the concept of Identity of Objects, this identity is represented by an integer and can be obtained through the native function id().

The contents of objects can also be retrieved through their identifier by means of the method cast() provided by the standard library ctypes.

See just how your code could be rewritten in Python:

import ctypes

# Valor
val = 35

# Recupera a identidade de "Valor"
x = id(val)

# A partir da identidade de "Valor"
# eh possivel recuperar o seu conteudo
y = ctypes.cast( x, ctypes.py_object ).value

print(val);
print(x);
print(y);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.