我想用swig将一个从std::vector派生的类和一些扩展函数包装到csharp中。还需要vector中的函数,如push_back,以将新项添加到类中(在csharp中命名为Add
(。
我尝试了swig的默认设置,IntArray在csharp中有效。但是,vector的函数无效。
如果我试图在.i文件中定义一个向量:
namespace std{
%template(ScalarVec) vector<ScalarTest>;
}
一个名为ScalarVec的类具有类似vector的函数,这在csharp中是有效的,但没有扩展函数。
如何用swig将ScalarArray封装到csharp
下面是一个简单的例子。
#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对声明的顺序很挑剔。下面正确地包装了您的示例代码,并且可以调用sum
函数。我没有为C#设置,所以这个演示是为Python:创建的
test.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
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)
输出:
sum 3
1 2