C언어

[APR] character string handling

고요한하늘... 2009. 1. 30. 17:14

8.  character string handling

 

c개발자라면  strlen()또는 strcpy() 와 같은 문자열 API에 익숙할 것이다. libapr에서도 문자열 API를 제공한다. ANSI c와 거의 유사하다. 왜 libapr은 약간 다른 문자열 APR을 제공하는가?
libapr 문자열 API의 장점은 메모리 플과 관련이 있다. C언어의  문자열 처리에서는 메모리 처리와 관련된 여러가지 적업을 해야한다. 아래 예제 코드를 보면

/* ANSI C string example (a bit naive code) */
/* we concatenate three strings, s1, s2, s3 */
int len1 = strlen(s1);
int len2 = strlen(s2);
int len3 = strlen(s3);
int total_len = len1 + len2 + len3;
char *cat_str = malloc(total_len + 1);
strcpy(cat_str, s1);
strcat(cat_str, s2);
strcat(cat_str, s3);

/* later, we have to free the allocated memory */
free(cat_str);


libapr로 작성된 코드를 보면

/* pseudo code about libapr string APIs */
apr_pool_t *mp;
apr_pool_create(&mp, NULL);

/* apr_pstrcat() takes care of both memory allocation and string concatenation.
 * If the concatenated string is read-only, we should use 'const char*' type. */
const char *cat_str = apr_pstrcat(mp, s1, s2, s3, NULL);

/* later, all we have

apr_pstrcat(), apr_psprintf()와 같은 함수는 매우 단순화 코드로 구현이 가능하도록 해주고 있다. 이런 함수 목록은  apr_strings.h에 있다.