Skip to content

5. 内联汇编与宏

5.1 c.Asm — 内联汇编

5.1.1 单行

import c

c.Asm('nop')
c.Asm('cli')

生成 C:

__asm__ volatile ("nop");
__asm__ volatile ("cli");

5.1.2 多行

import c

c.Asm(""".intel_syntax noprefix
mov eax, cr0
and eax, 0x9ffffff
mov cr0, eax
fninit""")

生成 C:

__asm__ volatile (
    ".intel_syntax noprefix\n\t"
    "mov eax, cr0\n\t"
    "and eax, 0x9ffffff\n\t"
    "mov cr0, eax\n\t"
    "fninit"
    );

多行汇编自动用 \n\t 换行,生成 GCC 扩展汇编格式。

5.2 c.Macro — 宏定义

import c

def TestMacro():
    c.Macro('MAX_VALUE', '100')
    c.Macro('PI', '3.14159')

生成 C:

#define MAX_VALUE 100
#define PI 3.14159

5.3 c.Memory — 字面地址

将整数常量转为 void* 指针:

import c

addr = c.Memory(0x1000)      # ((void *)0x1000)

生成 C:

int addr = ((void *)4096);

5.4 c.TypeCast — 强制类型转换

import c

x: int = 42
y = c.TypeCast('float', x)   # ((float)x)

生成 C:

int y = ((float)x);

5.5 c.Addr / c.Cast — 取地址 & 解引用

import c

ptr = c.Addr(x)              # &x
val = c.Cast(ptr)            # *(ptr)

生成 C:

ptr = &x;
val = *(ptr);

5.6 c.Ptr — 指针赋值

import c

c.Ptr(0x1000, 42)            # *((void *)0x1000) = 42
c.Ptr(0x2000)                # ((void *)0x2000)

生成 C:

*((void *)4096) = 42;
((void *)8192);

5.7 头文件包含

import stdio                # #include <stdio.h>
import myheader             # #include "myheader.h"

生成 C:

#include <stdio.h>
#include "myheader.h"

stdio 被识别为标准库 → <> 形式。其他名称作为本地头文件 → "" 形式。 import cimport t 被翻译器跳过(内部实现)。

5.8 限制

TransPyC 目前不支持: - 函数式宏 - 条件编译(#ifdef / #ifndef) - #pragma / #line / __attribute__