SWIG with Eigen3::Vector3d and std::vector<Vector3d>
<p>The corresponding gist is <a href="https://gist.github.com/nschloe/5e213272671db5dd745508093f37a4a1" rel="nofollow">here</a>.</p>

<hr>

<p>I'd like to use SWIG to call a bunch of C++ function from Python, specifically functions that accept vectors. So far, I've implemented it all with <code>std_vector.i</code> and <code>std::vector&lt;double&gt;</code>, but since I end of converting it all into <code>Eigen::Vector3d</code> anyways, I thought I might better make it native. A small C++ example is</p>



<pre><code>#ifndef MYTEST_HPP
#define MYTEST_HPP

#include &lt;iostream&gt;
#include &lt;Eigen/Dense&gt;

void
print_norm(const Eigen::Vector3d &amp; x) {
  std::cout &lt;&lt; x.norm() &lt;&lt; std::endl;
}

void
print_norms(const std::vector&lt;Eigen::Vector3d&gt; &amp; xs) {
  for (const auto &amp; x: xs) {
      std::cout &lt;&lt; x.norm() &lt;&lt; std::endl;
  }
}

#endif // MYTEST_HPP
</code></pre>

<p>I have no idea though how to best call this from Python. Perhaps</p>



<pre><code>import mytest

a = [1, 1, 0]
mytest.print_norm(a)
</code></pre>

<p>this is reasonable? A <code>numpy.array</code> might also work. Either way, I have no idea what to put in my <code>mytest.i</code>.</p>

<p>Any hints?</p>

<p>There are a few examples of wrapping Eigen types with NumPy floating around on the web, where the <a href="https://github.com/Biomechanical-ToolKit/BTKCore/blob/master/Utilities/SWIG/eigen.i" rel="nofollow">Biomechanical Toolkit</a> implementation is the most widely copied, and I would recommend using that one too. It looks relatively big, but that's mostly from all the sanity checks and separate templates for different types.</p>

<p>Conversion from NumPy to Eigen works by using the <code>obj_to_array_contiguous_allow_conversion</code> function from the accompanying <a href="https://github.com/Biomechanical-ToolKit/BTKCore/blob/master/Utilities/SWIG/numpy.i" rel="nofollow"><code>numpy.i</code></a>, followed by <code>PyArray_DATA</code> to get the data as a contiguous C(++) array, from which the data is simply assigned to each coefficient in the Eigen matrix separately.</p>

<p>The other way around is pretty much the inverse: a python NumPy array is created with <code>PyArray_SimpleNew</code>, which is filled with data from the Eigen matrix.</p>

<p>It doesn't directly do the wrapping for <code>std::vector&lt;Eigen::Vector3d&gt;</code>, you can set that up using <code>%include &lt;stl.i&gt;</code> probably, but in my experience it would be better to use Nx3 numpy arrays as lists of 3D vectors, because of the issues with Eigen, alignment and STL containers.</p>

python c++ swig eigen eigen3