如何在python中字符串化swig矩阵对象 [英] How to stringfy a swig matrix object in python

查看:29
本文介绍了如何在python中字符串化swig矩阵对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 openbabel 的 swig 包装器(用 C++ 编写,并提供一个 Python 包装器通过swig)

I am using swig wrapper of openbabel (written in C++, and supply a python wrapper through swig)

下面我只是用它来读取分子结构文件并获取它的晶胞属性.

Below i just use it to read a molecule structure file and get the unitcell property of it.

import pybel
for molecule in pybel.readfile('pdb','./test.pdb'):
    unitcell = molecule.unitcell
    print unitcell
   |..>     
   |..>     
<openbabel.OBUnitCell; proxy of <Swig Object of type 'OpenBabel::OBUnitCell *' at 0x17b390c0> >

单元格有函数 CellMatrix(),

The unitcell has function CellMatrix(),

unitcell.GetCellMatrix()
   <22> <openbabel.matrix3x3; proxy of <Swig Object of type 'OpenBabel::matrix3x3 *' at 0x17b3ecf0> >

OpenBabel::matrix3x3 类似于:

the OpenBabel::matrix3x3 is something like :

1 2 3
4 5 6
7 8 9

我想知道如何打印出 matrix3*3 的内容.我已经尝试过 __str____repr__ .

i am wondering how to print out the contents of the matrix3*3 . I have tried __str__ and __repr__ with it.

在python中对由swing包裹的矩阵内容进行字符串化的一般方法是什么?

Any general way to stringfy the contents of a matrix wrapped by swing in python ?

谢谢

推荐答案

基于这个 openbabel 文档,看起来 Python 绑定没有提供打印 matrix3x3 对象的好方法是有充分理由的.matrix3x3 C++ 类重载了 << 运算符,SWIG 将忽略该运算符:

Based on this openbabel documentation, it looks like there is a good reason the Python bindings don't come with a nice way to print a matrix3x3 object. The matrix3x3 C++ class overloads the << operator, which SWIG will simply ignore:

http://openbabel.org/api/2.2.0/classOpenBabel_1_1matrix3x3.shtml

这意味着您需要修改 SWIG 接口文件(查看 http://www.swig.org/Doc1.3/SWIGPlus.html#SWIGPlus_class_extension) 在 C++ 中将 __str__ 方法添加到 openbabel::matrix3x3它包装了 << 运算符.你的方法可能看起来很像

This means that you'll need to modify your SWIG interface file (look at http://www.swig.org/Doc1.3/SWIGPlus.html#SWIGPlus_class_extension) to add a __str__ method to openbabel::matrix3x3 in C++ which wraps the << operator. Your method might look a lot like

std::string __str__() {
  //make sure you include sstream in the SWIG interface file
  std::ostringstream oss(std::ostringstream::out);
  oss << (*this);
  return oss.str();
}

我相信在这种情况下,SWIG 将正确处理 C++ 返回类型 std::string,但如果不是,您可能需要处理返回字符数组.

I believe that SWIG will properly handle C++ a return type of std::string in this case, but if not you might have to play around with returning a character array.

此时,您应该能够重新编译绑定,并重新运行您的 Python 代码.在 matrix3x3 对象上调用 str() 现在应该显示在 C++ 中使用 << 运算符显示的内容.

At this point, you should be able to recompile the bindings, and rerun your Python code. Calling str() on a matrix3x3 object should now display what would be displayed with the << operator in C++.

这篇关于如何在python中字符串化swig矩阵对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆