基本上是照着《python源码剖析》里面的代码写的,当然它有一点细节的地方没有指出来,我也就补全了一下,
先来看下运行的效果图:
下面直接上代码:
#include<iostream>
#include<string.h>
#include<iterator>
#include<stdlib.h>
#include<stdio.h>
#include<memory>
#include<map>
#include<ctype.h>
using namespace std;
#define PyObject_HEAD \
int refCount; \
struct tagPyTypeObject *type
#define PyObject_HEAD_INIT(typePtr) \
0,typePtr
typedef struct tagPyObject
{
PyObject_HEAD;
}PyObject;
typedef void (*PrintFun)(PyObject*object);
typedef PyObject* (*AddFun)(PyObject* left,PyObject*right);
typedef long (*HashFun)(PyObject* object);
typedef struct tagPyTypeObject
{
PyObject_HEAD;
char* name;
PrintFun print;
AddFun add;
HashFun hash;
}PyTypeObject;
PyTypeObject PyType_Type =
{
PyObject_HEAD_INIT(&PyType_Type),
"type",
0,
0,
0
};
typedef struct tagIntObject
{
PyObject_HEAD;
int value;
}PyIntObject;
static void int_print(PyObject*object);
static PyObject* int_add(PyObject*left,PyObject* right);
static long int_hash(PyObject* object);
PyTypeObject PyInt_Type =
{
PyObject_HEAD_INIT(&PyType_Type),
"int",
int_print,
int_add,
int_hash
};
PyObject* PyInt_Create(int value)
{
PyIntObject *object = new PyIntObject;
object->refCount = 1;
object->type = &PyInt_Type;
object->value = value;
return (PyObject*)object;
}
static void int_print(PyObject*object)
{
PyIntObject* intObject = (PyIntObject*)object;
printf("%d\n",intObject->value);
}
stati