SWIG - 如何使用采用 'const double*' 的构造函数将 python 包装成 class

SWIG - How to wrap to python a class with a constructor that takes a 'const double*'

我必须使用 Swig 将向量(几何向量)class 从 C++ 包装到 Python。 此 Vector3 class 的构造函数之一接受 const double*:

Vector3(const double* list);

我想把它包装起来,这样我就可以在 Python:

vec = Vector3([1, 2, 3])

有什么建议吗?

我建议将原型更改为

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++'],
                  )])

您可以为 const double* list 编写特定的输入类型映射。请注意,此示例没有为简洁起见进行错误检查,并包含用于测试目的的内联 class:

%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));
     = 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