在9.3节的实验中,BINARY_ADD的修改没有给出源代码,这里给出我的源代码:星号注释里面是增加的代码
首先在虚拟机主循环部分先声明我们需要的变量,因为C必须在开头声明变量,不然会报错
// 虚拟机主循环
for (;;) {
/************************BINARY_ADD***************************/
PyObject* target = PySys_GetObject("stdout");
char temp[256] = {0};
/************************BINARY_ADD***************************/
#ifdef WITH_TSC
然后在BINARY_ADD里面加入代码:
TARGET_NOARG(BINARY_ADD)
{
w = POP();
v = TOP();
if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
/* INLINE: int + int */
// PyIntObject对象相加的快速通道
register long a, b, i;
a = PyInt_AS_LONG(v);
b = PyInt_AS_LONG(w);
/* cast to avoid undefined behaviour
on overflow */
i = (long)((unsigned long)a + b);
/************************BINARY_ADD***************************/
sprintf(temp, "[BINARY_ADD] : \"%d+%d\" in quick channel...%s\n", a, b, ((i^a) < 0 && (i^b) < 0) ? "Overflow":"Success");
PyFile_WriteString(temp, target);
/************************BINARY_ADD***************************/
// 如果加法溢出,则转向慢速通道
if ((i^a) < 0 && (i^b) < 0){
/************************BINARY_ADD***************************/
PyObject* target = PySys_GetObject("stdout");
char temp[256] = {0};
sprintf(temp, "[BINARY_ADD] : \"%d+%d\" switch to slow channel...\n", a, b);
PyFile_WriteString(temp, target);
/************************BINARY_ADD***************************/
goto slow_add;
}
最后在release下进行项目生成,最后实验结果如下: