gpt4 book ai didi

php - 模板类型作为 SWIG 中的结构数据成员

转载 作者:可可西里 更新时间:2023-11-01 13:26:51 24 4
gpt4 key购买 nike

我正在使用 SWIG 为 C++ 库编写 PHP 包装器,但我在使用具有模板类型实例作为数据成员的结构时遇到了问题。

假设我有以下头文件:

template <typename>
struct myvector
{
};

struct S
{
myvector<int> v;
};

myvector<int> foo();
S bar();

和接口(interface)文件:

%module test
%{
#include "test.hpp"
%}

%include "test.hpp"
%template(IntVec) myvector<int>;

当我尝试使用直接返回 myvector 的函数时,它工作正常:

$v1 = test::foo();

但是,当我尝试使用返回 S 对象的函数,并尝试访问其类型为 myvector 的数据成员时:

$s = test::bar();
$v2 = $s->v;

我在运行时遇到以下错误:

PHP Fatal error:  Class 'myvectorT_int_t' not found in test.php on line 145

我的界面文件中可能缺少某些内容,但我不知道是什么。谁能帮忙?

最佳答案

据我所知,这是一个 SWIG 错误。别人有already reported it实际上。幸运的是,通过 PHP 的 class_alias 有一个简单、可靠的解决方法:

%module test
%{
#include "test.h"
%}

%pragma(php) code="
# This code is inserted as a workaround for template bugs with SWIG
class_alias('IntVec', 'myvectorT_int_t');
"

%include "test.h"
%template(IntVec) myvector<int>;

此处的 pragma 插入代码以在生成的 PHP 文件的开头设置别名。

(还有另一种可能的解决方法 - 而不是通过 getter/setter 函数使用公共(public)成员变量访问按预期工作)

bug report还提到了另一种可能的解决方法,尽管我并不热衷于此,因为它需要为模板类型使用一个相当丑陋的名称。


错误假设的理由

__get 的代码包括:

$c=substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));
return new $c($r);

当你到达这里时$c设置为 myvectorT_int_t这将是正确的,除了 %template指令。

当我们添加 myvector<int> get()功能S生成的代码导致:

 $c=substr(get_resource_type($r), (strpos(get_resource_type($r), '__') ? strpos(get_resource_type($r), '__') + 2 : 3));
if (!class_exists($c)) {
return new IntVec($r);
}
return new $c($r);

其中至关重要的是包含在没有 %template 的情况下也是正确的通用代码作为特殊检查,看它是否真的是IntVec .

Source/Modules/php.cxx 中也有评论:

// FIXME: Currently we always use call_user_func for __get, so we can
// check and wrap the result. This is needless if all the properties
// are primitive types. Also this doesn't handle all the cases which
// a method returning an object does.

最终由同一个接口(interface)文件为Java生成的代码是正确的。

关于php - 模板类型作为 SWIG 中的结构数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com