如何让 boost::python 遵循数据对齐?

73 阅读2分钟

我在编写项目的 Python 包装器,该项目使用 Eigen 进行数学运算。在测试基本操作后,在 Python 中创建的 eigen 对象总是返回不正确的结果。当我使用 Eigen::aligned_allocator 没有遵循数据对齐时,通常会发生这种情况。可以通过使用 Eigen::aligned_allocator 分配 eigen 对象来解决此问题。如何告诉 boost 使用 Eigen::aligned_allocator 分配 eigen 对象?

huake_00044_.jpg 以下是一个简单的测试:

using namespace boost::python;
using namespace Eigen;

class_<Isometry3d>("Isometry3d", init<>())
    .def("__str__", make_function(IsometryToStr)) 
    .def_readonly("Identity", Isometry3d::Identity())
;

IsometryToStr 函数仅仅使用 Eigen 定义的运算符 <<。

Python:

a = Isometry3d.Identity
print a

我们希望它打印单位矩阵,但结果却总是不一样。

2、解决方案

要控制 C++ 类型的分配,请使用 make_constructor 将工厂函数作为 Python 对象的构造函数进行注册。通常情况下,自定义分配也意味着自定义释放,在这种情况下,可以使用 boost::shared_ptr 来管理对象的生存期并调用自定义释放策略。这个答案会更详细地介绍,但这里是一个完整的示例,其中包含一个基本自定义分配器。

#include <cstdlib>
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>

///  @brief Basic custom allocator.
template <typename T>
class custom_allocator
{
public:
  typedef size_t size_type;
  typedef T*     pointer;
  typedef T      value_type;
public:
  pointer allocate(size_type num, const void* hint = 0)
  {
    std::cout << "custom_allocator::allocate()" << std::endl;
    return reinterpret_cast<pointer>(
      std::malloc(num * sizeof(value_type)));
  }

  void deallocate(pointer p, size_type num)
  {
    std::cout << "custom_allocator::deallocate()" << std::endl;
    std::free(p);
  }
};

/// @brief Example class.
class foo
{
public:
  foo()         { std::cout << "foo()" << std::endl; }
  ~foo()        { std::cout << "~foo()" << std::endl; } 
  void action() { std::cout << "foo::action()" << std::endl; }
};

/// @brief Allocator for foo.
custom_allocator<foo> foo_allocator;

/// @brief Destroy a foo object.
void destroy_foo(foo* p)
{
  p->~foo();                      // Destruct.
  foo_allocator.deallocate(p, 1); // Deallocate.
}

/// @brief Factory function to create a foo object.
boost::shared_ptr<foo> create_foo()
{
  void* memory = foo_allocator.allocate(1); // Allocate.
  return boost::shared_ptr<foo>(
    new (memory) foo(), // Construct in allocated memory.
    &destroy_foo);      // Use custom deleter.
}

BOOST_PYTHON_MODULE(example) {
  namespace python = boost::python;
  // Expose foo, that will be managed by shared_ptr, and transparently
  // constructs the foo via a factory function to allow for a custom
  // deleter to use the custom allocator.
  python::class_<foo, boost::shared_ptr<foo>, 
                 boost::noncopyable>("Foo", python::no_init)
    .def("__init__", python::make_constructor(&create_foo))
    .def("action", &foo::action)
    ;
}

用法:

>>> import example
>>> f = example.Foo()
custom_allocator::allocate()
foo()
>>> f.action()
foo::action()
>>> f = None
~foo()
custom_allocator::deallocate()