书中的代码没有给完整,而且有一些bug,可能是版本的不同,我的编译环境是VS2010。
文件目录:





SmallPython.cpp的代码:
// SmallPython.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
using namespace std;
/***********************************PyObject**********************************/
#define PyObject_HEAD \
int refCount; \
struct tagPyTypeObject *type
#define PyObject_HEAD_INIT(typePtr)\
0, typePtr
typedef struct tagPyObject
{
PyObject_HEAD;
}PyObject;
/***********************************PyObject**********************************/
/***********************************PyTypeObject**********************************/
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"
};
/***********************************PyTypeObject**********************************/
/***********************************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
};
typedef struct tagPyIntObject
{
PyObject_HEAD;
int value;
}PyIntObject;
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);
}
static PyObject* int_add(PyObject* left, PyObject* right)
{
PyIntObject* leftInt = (PyIntObject*)left;
PyIntObject* rightInt = (PyIntObject*)right;
PyIntObject* result = (PyIntObject*)PyInt_Create(0);
if(result == NULL)
{
printf("We have no enough memory!!"

本文介绍了一个简单的自制Python解释器实现,包括整数、字符串及字典等基础类型的处理,并通过命令行进行交互式输入和执行。
最低0.47元/天 解锁文章
3272

被折叠的 条评论
为什么被折叠?



