C pointers handled in python

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 want to make this code run within a program in python . How do I do? I'm starting in python but I want to work with pointers by merging the languages, because until then I have not figured out how to do this with just python .

    
asked by anonymous 09.01.2018 / 19:04

1 answer

1

Roughly , within the standard Python data model, pointers can be seen 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() .

Object content can also be retrieved through its identifier through the cast() available from the standard library ctypes .

See 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);
    
11.01.2018 / 16:26