swig模板 PHP,php – 强制类型SWIG

遗憾的是,由于包装器的生成方式,您无法完全摆脱铸件.

但是,您可以拦截基本数据类型并将它们重定向到模板函数,如下所示:

%module sphp

%{

#include

extern int hello(char *str);

template

int hello(const T &)

{

std::cout << "unsupported data type" << std::endl;

}

%}

extern int hello(char *str);

template

int hello(const T &);

%template(hello) hello;

要拦截更多数据类型,只需添加一个新的运算符重载:

%template(hello) hello;

更新:

这是一个更加困难的方法,可以通过覆盖SWIG的typemaps来实现.这取自SWIG的PHP类型映射并进行修改以防止它转换值.

%module sphp

%{

extern int hello(char *str);

%}

%typemap(in) char *

{

if ((*$input)->type != IS_STRING)

SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected string");

$1 = ($1_ltype) Z_STRVAL_PP($input);

}

%typemap(in) (char *STRING, int LENGTH), (char *STRING, size_t LENGTH) {

if ((*$input)->type != IS_STRING)

SWIG_PHP_Error(E_ERROR, "Type error in argument $argnum of $symname. Expected string");

$1 = ($1_ltype) Z_STRVAL_PP($input);

$2 = ($2_ltype) Z_STRLEN_PP($input);

}

extern int hello(char *str);

输出:

php > include ("sphp.php");

php > hello("test");

Hello World: test

php > hello(3);

PHP Fatal error: Type error in argument 1 of hello. Expected string in php shell code on line 1

php > hello([]);

PHP Fatal error: Type error in argument 1 of hello. Expected string in php shell code on line 1

php >

这更加乏味,因为如果你想完全摆脱自动参数转换,你必须以相同的方式覆盖每一种类型,另一方面它可以让你更好地控制参数转发的行为.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值