如何为IronPython访问封装C++代码
我有一个简单的例子,想在Ironpython中使用(我之前用的是普通的Python),所以我在把我的C++代码导入到Ironpython时遇到了困难。通常我只需要用SWIG把我的代码包装一下,然后导入,就可以继续我的工作了。
但是因为Ironpython是基于C#的,而不是C语言,这让这个过程变得更加复杂。
我该如何为Ironpython包装这个类呢?(我还附上了我的SWIG文件作为例子,但可能没什么用)
#include "minimal.h"
double average(std::vector<int> v) {
return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
}
std::vector<double> half(const std::vector<double>& v) {
std::vector<double> w(v);
for (unsigned int i = 0; i<w.size(); i++)
w[i] /= 2.0;
return w;
}
void halve_in_place(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>(), 2.0));
}
还有头文件
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
double average(std::vector<int> v);
std::vector<double> half(const std::vector<double>& v);
void halve_in_place(std::vector<double>& v);
我有一个SWIG的i文件叫minimal.i,但我意识到在运行swig.exe -c++ -python "%(FullPath)"时会遇到很多问题,Ironpython在导入时也无法接受这个。
%module transfervector
%{
#include "minimal.h"
%}
%include "std_vector.i"
// Instantiate templates used by example
namespace std {
%template(IntVector) vector<int>;
%template(DoubleVector) vector<double>;
}
// Include the header file with above prototypes
%include "minimal.h"
1 个回答
2
SWIG-python 是不行的,因为它生成的是 CPython 扩展,而 IronPython 不支持这些扩展。
最终,你需要把 C++ 的代码包装一下,这样才能在 .NET 中使用。我觉得你可以用 SWIG 来生成 C# 的包装代码,然后再把这些代码导入到 IronPython 中。或者,你也可以用 C++/CLI 编译器直接生成一个 .NET 的程序集,这样也能在 IronPython 中使用。