[英]How to wrap a class derived from vector in swig
I want to wrap a class derived from std::vector with some extend functions into csharp with swig.我想将派生自 std::vector 的 class 和一些扩展函数包装到带有 swig 的 csharp 中。 the functions from vector are also needed like push_back to add new item into the class (which named
Add
in csharp). vector 中的函数也需要像 push_back 来将新项目添加到 class(在 csharp 中命名为
Add
)。
I tried with default setting with swig, IntArray is valid in csharp.But, vector's functions are invalid.我尝试使用 swig 的默认设置,IntArray 在 csharp 中有效。但是,向量的函数无效。
if i try to define a vector in the.i file:如果我尝试在 .i 文件中定义一个向量:
namespace std{
%template(ScalarVec) vector<ScalarTest>;
}
a class named ScalarVec have functions like vector is valid in csharp, but without the extend function.名为 ScalarVec 的 class 具有类似于 vector 的函数在 csharp 中有效,但没有扩展 function。
How to wrap the ScalarArray to csharp with swig?如何用 swig 将 ScalarArray 包装成 csharp?
The following is a simple example.下面是一个简单的例子。
#include <vector>
#include <numeric>
namespace test
{
struct ScalarTest {
int val;
};
struct ScalarArray : public std::vector<ScalarTest>
{
int sum() const {
int res = 0;
for (const ScalarTest &item : *this) {
res += item.val;
}
return res;
}
};
}
SWIG is picky about order of declarations. SWIG 对声明的顺序很挑剔。 Below correctly wraps your example code and can call the
sum
function. I'm not set up for C# so the demo is created for Python:下面正确包装了您的示例代码,可以调用
sum
function。我没有设置 C#,所以演示是为 Python 创建的:
test.i测试.i
%module test
%{
// Code to wrap
#include <vector>
#include <numeric>
namespace test
{
struct ScalarTest {
int val;
};
struct ScalarArray : public std::vector<ScalarTest>
{
int sum() const {
int res = 0;
for (const ScalarTest &item : *this) {
res += item.val;
}
return res;
}
};
}
%}
namespace test
{
struct ScalarTest {
int val;
};
}
%include <std_vector.i>
// Must declare ScalarTest above before instantiating template here
%template(ScalarVec) std::vector<test::ScalarTest>;
// Now declare the interface for SWIG to wrap
namespace test
{
struct ScalarArray : public std::vector<ScalarTest>
{
int sum() const;
};
}
demo.py演示.py
import test
x = test.ScalarArray()
a = test.ScalarTest()
a.val = 1
b = test.ScalarTest()
b.val = 2
x.push_back(a)
x.push_back(b)
print('sum',x.sum())
print(x[0].val,x[1].val)
Output: Output:
sum 3
1 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.