struct _longobject {
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
Py_ssize_t ob_size;
digit ob_digit[1];
}PyLongObject;
PyLongObject *p;
/*为结构体动态分配内存*/
p = (PyLongObject*)malloc(sizeof(PyLongObject)+sizeof(digit)*abs(ob_size))
for(int i = 0; i < ob_size; i++){
p->ob_digit[i] = 1;
}
这就是PyLongObject对象的内存分配,只不过python源码由内存管理模块进行内存的分配,不那么好理解。
example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct T
{
int a;
int b;
char c[0];
}T;//大小为8字节,在32位操作系统
int main(int argc, char *argv[]){
T *t = (T*)malloc(sizeof(T)+sizeof(char)*6);
printf("%lu,%lu,%lu\n",sizeof(T),sizeof(int),sizeof(t->c));
t->a = 1;
t->b = 1;
strcpy(t->c, "hello");
printf("%s\n",t->c);
return 0;
}
输出:
8,4,0
hello