Superkkt Blog

C를 사용해서 PHP에서 사용할 API를 만들수 있다. API를 로드하는방법은 PHP를 초기에 컴파일할 때 포함하는 방법이 있고 나중에 동적으로 로드하는 방법이 있다. 동적으로 로드할때는 phpcode에서 dl함수를 사용해서 라이브러리를 로드해야 한다.

우선 아래와 같이 C 코드를 만든다.

* func.c

Code:
#include <string.h>

int
strlen_kkt(char *string)
{
        return strlen(string);
}



그리고 php에서 사용할 함수를 아래와 같이 만든다.

* php_func.c

Code:
#include "php.h"
#include "func.h"

/* compiled function list so Zend knows what's in this module */
function_entry func_functions[] =
{
    PHP_FE(strlen_php, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry func_module_entry =
{
    STANDARD_MODULE_HEADER,
    "KKT test API",
    func_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    "0.1",
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_FUNC
ZEND_GET_MODULE(func)
#endif

PHP_FUNCTION(strlen_php)
{
        zval **string1;

        if(ZEND_NUM_ARGS() != 1 ||
                       zend_get_parameters_ex(1, &string1) == FAILURE) {
                WRONG_PARAM_COUNT;
        }

        convert_to_string_ex(string1);

        RETURN_LONG(strlen_kkt(Z_STRVAL_PP(string1)));
}




* func.h
int strlen_kkt(char *string);
PHP_FUNCTION(strlen_php);




모든 소스 파일을 /usr/local/include/php/ext에 위치 시키고 아래와 같이 컴파일 한다.

# gcc -fpic -DCOMPILE_DL_FUNC=1 -I/usr/local/include -I../../TSRM -I../.. -I../../main -I../../Zend -c -o func.o func.c

# gcc -fpic -DCOMPILE_DL_FUNC=1 -I/usr/local/include -I../../TSRM -I../.. -I../../main -I../../Zend -c -o php_func.o php_func.c

# gcc -shared -L/usr/local/lib -o func.so func.o php_func.o



그리고 php.ini에서 extension_dir 변수를 적절하게 조정한 후 그 디렉토리로 func.so 파일을 복사한다.

이제 php code에서 strlen_php 함수를 사용 할 수 있다.

<?

dl('func.so');

echo strlen_php("abcd");

?>



php_func.c에서 사용된 문법이나 정적으로 모듈을 포함시키는 방법들은 아래 링크를 참조하기 바람.

http://www.php.net/manual/kr/zend.php
2006/03/19 20:13 2006/03/19 20:13

trackbacks

trackbacks rss

이 글에는 트랙백을 보낼 수 없습니다

Leave a Comment