Php 强制类型SWIG
所以我有下面的C++Php 强制类型SWIG,php,c++,swig,Php,C++,Swig,所以我有下面的C++ #include <stdio.h> #include <iostream> #include <vector> using namespace std; int hello(char *str); int hello(char *str) { cout << "Hello World: " << str << endl; return 0; } 我可以在php中编译和使用它 ph
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
int hello(char *str);
int hello(char *str) {
cout << "Hello World: " << str << endl;
return 0;
}
我可以在php中编译和使用它
php> hello("testing!");
这一切都是邪恶的
唯一的问题是
php> hello(3);
仍然有效。我不想要这个,看起来斯威格很安静
/*@SWIG:/usr/share/swig2.0/php/utils.i,62,CONVERT_STRING_IN@*/
if ((*args[0])->type==IS_NULL) {
arg1 = (char *) 0;
} else {
convert_to_string_ex(args[0]);
arg1 = (char *) Z_STRVAL_PP(args[0]);
}
/*@SWIG@*/;
现在我不想编辑包装器,因为它是自动生成的。有没有一种方法可以关闭这种静默转换,这样
hello(3)
将抛出异常或错误,或者我可以给hello
一个关于最初传递的php参数类型的提示?遗憾的是,由于包装器是如何生成的,您无法完全摆脱转换。
但是,您可以截取基本数据类型并将其重定向到模板函数,如下所示:
%module sphp
%{
#include <iostream>
extern int hello(char *str);
template<class T>
int hello(const T &)
{
std::cout << "unsupported data type" << std::endl;
}
%}
extern int hello(char *str);
template<class T>
int hello(const T &);
%template(hello) hello<int>;
输出:
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 >
这更为乏味,因为如果您想完全摆脱自动参数转换,您必须以相同的方式覆盖每一种类型,另一方面,它让您可以更好地控制参数转发的行为。您可以尝试使用explicit关键字,它会停止隐式转换:转换发生在调用之前。当一个数字传递给它时,你希望包装器做什么?或者抛出一个错误,或者让C++函数调用它知道它没有通过一个字符串,这样我就可以抛出一个字符串。error@Joe:是的,对于构造函数,不是任何旧函数调用。这很好,但是有没有一个明确的PHP将传递给SWIGYes的类型列表,这都在列表中。
%template(hello) hello<double>;
%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 >