gpt4 book ai didi

php - Swig 将 vector 转换为原生 PHP 数组

转载 作者:行者123 更新时间:2023-11-30 05:20:49 30 4
gpt4 key购买 nike

我开始使用 swigphp ,我想返回一个 std::vector<std::string>到我的php code.I have try this (all compilation work).

我的痛饮文件:

%module example
%include <std_string.i>
%include <std_vector.i>

%{
extern std::vector<std::string> testSwig(const char *path);
%}

//try here to convert vector to native php array
%typemap(out) const std::vector<std::string> & {
array_init($result);
Array::const_iterator i = $1->begin();
Array::const_iterator e = $1->end();
for(; i != e; ++i ) {
zval * data;
MAKE_STD_ZVAL(data);
ZVAL_STRINGL(data, (char*)i->c_str(), i->size(), 1);
zend_hash_next_index_insert( HASH_OF($result), &data, sizeof(zval *), NULL );
}
}

extern std::vector<std::string> testSwig(const char *path);

我的cpp文件:

#include <iostream>
#include <vector>

std::vector<std::string> testSwig(const char *path)
{
std::vector<std::string> v;
v.push_back("test 1");
v.push_back("test 2");
v.push_back("try vector");

return v;
}

最后我的 php 文件来试试这个:

<?php
echo '<pre>';
echo print_r(testSwig('try arg'));
echo '</pre>';
?>

我的问题是我的转换 std::vectorphp数组不起作用;当我做我的print_r我有这个结果:resource(1) of type (_p_std__vectorT_std__string_t)

最佳答案

添加 Flexo 提供的答案。

在 PHP7 zend API 中 MAKE_STD_ZVAL() 宏被删除(包括一些其他的东西:https://wiki.php.net/phpng-upgrading)

为了使这个类型映射与 PHP7 一起工作,我这样做了:

%typemap(out) std::vector<std::string> {
array_init($result);
$1_type::const_iterator i = $1.begin();
$1_type::const_iterator e = $1.end();

for(; i != e; ++i ) {
add_next_index_string($result, (char*) i->c_str() );
}
}

php 的 testSwig 函数打印出预期的结果:

Array
(
[0] => test 1
[1] => test 2
[2] => try vector
)

关于php - Swig 将 vector<std::string> 转换为原生 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40502408/

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