我必须使用Swig将C ++中的矢量(几何向量)类包装到Python中。
此Vector3
类的构造函数之一接受const double*
:
Vector3(const double* list);
我想将它包装起来,以便我可以在Python中执行此操作:
vec = Vector3([1, 2, 3])
有什么建议吗?
答案 0 :(得分:5)
我建议将原型更改为
Vector(const double* list, size_t len);
使用
支持构造的完整示例import example
v = example.Vector([1.0,2.0,3.0])
example.h文件
#pragma once
#include <cstdlib>
class Vector {
public:
Vector();
Vector(double x, double y, double z);
Vector(const double* list, size_t len);
};
example.cpp
#include "example.h"
#include <iostream>
Vector::Vector() {
std::cout << "Vector()" << std::endl;
}
Vector::Vector(double x, double y, double z) {
std::cout << "Vector(double, double, double)" << std::endl;
}
Vector::Vector(const double* list, size_t len) {
std::cout << "Vector(const double*)" << std::endl;
}
example.i
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include "numpy.i"
%init {
import_array();
}
%apply (double* IN_ARRAY1, size_t DIM1) \
{(const double* list, size_t len)}
%include "example.h"
setup.py
from distutils.core import setup, Extension
setup(name="example",
py_modules=['example'],
ext_modules=[Extension("_example",
["example.i","example.cpp"],
swig_opts=['-c++'],
)])
答案 1 :(得分:4)
您可以为const double* list
编写特定的输入类型图。请注意,为简洁起见,此示例没有错误检查,并包含用于测试目的的内联类:
%module test
%include <windows.i>
%typemap(in) const double* list (double value[3]) %{
for(Py_ssize_t i = 0; i < 3; ++i)
value[i] = PyFloat_AsDouble(PySequence_GetItem($input, i));
$1 = value;
%}
%inline %{
#include <iostream>
using namespace std;
class __declspec(dllexport) Vector3
{
public:
Vector3(const double* list)
{
cout << list[0] << ',' << list[1] << ',' << list[2] << endl;
}
};
%}
输出:
>>> import test >>> v = test.Vector3([1.1,2.2,3.3]) 1.1,2.2,3.3