[英]SWIG - How to wrap to python a class with a constructor that takes a 'const double*'
我必须使用 Swig 将向量(几何向量)类从 C++ 包装到 Python。 此Vector3
类的构造函数之一接受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])
例子.h
#pragma once
#include <cstdlib>
class Vector {
public:
Vector();
Vector(double x, double y, double z);
Vector(const double* list, size_t len);
};
例子.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;
}
例子.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"
设置文件
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
编写特定的输入类型映射。 请注意,此示例没有为简洁起见进行错误检查,并包含一个用于测试目的的内联类:
%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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.