search

Home  >  Q&A  >  body text

php-extension - php扩展中实例化对象并调用方法

使用函数宏call_user_function调用类中的方法:
如下:

ZEND_FUNCTION(call_say){
//调用myclass中的say方法
zval *obj,*method_construct,*method_say,*name,*age;
int name_len,age_len;
zend_uint param_count=ZEND_NUM_ARGS();
zval *params[param_count];

MAKE_STD_ZVAL(obj);
MAKE_STD_ZVAL(method_construct);
MAKE_STD_ZVAL(method_say);

object_init_ex(obj, people_ce);

ZVAL_STRINGL(method_construct,"__construct",strlen("__construct"),1);
ZVAL_STRINGL(method_say,"say",strlen("say"),1);

//获取参数
if(zend_parse_parameters(param_count TSRMLS_CC,"ss",&name,&name_len,&age,&age_len)==FAILURE){
    WRONG_PARAM_COUNT;
}

params[0]=name;
params[1]=age;

//__construct中存在参数 
call_user_function(NULL, &obj, method_construct, NULL,param_count,params TSRMLS_CC); 
call_user_function(NULL, &obj, method_say,NULL,0,NULL TSRMLS_CC);

zval_ptr_dtor(&obj);
zval_ptr_dtor(&method_construct);
zval_ptr_dtor(&method_say);
return;

}

这个call_user_function好像用错了样的。执行出现 Segmentation fault ! 哪位大神帮看下!
我想要的效果:
类中的两个方法:

public function __construct($name,$age){
        $this->name=$name;
        $this->age=$age;
    }
    public function say(){
        echo "我叫{$this->name},我今年{$this->age}岁了";
    }

补充:自己解决了
retval没有设置就出现这个错误:
首先定义:zval *retval;
分配内存:MAKE_STD_ZVAL(retval)

call_user_function(NULL, &obj, method_say, retval, 0, NULL TSRMLS_CC)

segmentfault的人气好像不行。。。。

阿神阿神2902 days ago386

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-10 14:32:51

    学习了,刚好用到

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:32:51

    我比你更气人,我 retval 也没问题,现在还在查错中。。。

    reply
    0
  • Cancelreply