我假设你有某种dup_string
例程在新的内存块中复制一个字符串。这DUP日常一定要注意,源字符串有一个未知的长度,这将在执行复制时仅确定,是这样的:
char *dup_string (char *s)
{
char *d = realloc(strlen(s)+1);
memcpy (d, s, strlen(s)+1);
return d;
}
所以,你可以使用此功能透明地在您的来电者使用它代码和卡莱收尾,这样的...
/* Source code: your programming language */
str s;
s = "whatever...";
func (s);
生成的汇编代码会是这样的(例如使用IA32代码,和C调用约定):
[Caller: this block repeated for every string passed as parameter to a function]
push offset s
call dup_string ;string copy pointed by EAX
add esp,4 ;get rid of parameter
push eax
call func
add esp,4 ;get rid of parameter
...
...
[Callee]
push ebp
mov ebp,esp
mov esi,[ebp+8] ; ESI = pointer to string
...use string in ESI...
...
...
EPILOG
(this block repeated for every string passed as argument):
mov esi,[ebp+8] ;8 because in this example, it's the first argument.
call free /* standard free() function */
mov esp,ebp
ret
你通常可以在堆栈上分配动态数组相当容易,但它通常需要一个基本指针,因为偏移量会发生变化。看看在你选择的架构上如何实现alloca和C99可变长度数组。棘手的部分是在混合调用/数据堆栈上返回动态字符串。后一个问题的一个相对简单的解决方案是一个固定的返回缓冲区(例如,单个值的第二个“栈”),被调用者从该缓冲区中获得结果。 – doynax