将C++插入到Python中

2024-05-23 17:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个C++模块来计算我的SARCA机器人手臂的正运动学和逆运动学,我想把这个模块封装到Python中,这样我就可以在另一个应用程序中使用它。对于转换,我选择了SWIG,但要正确编写接口文件非常困难

在C++模块的头中,我有

namespace ARM_KINEMATICS{
    /*
       Forward kinematics
       [in] const double *q: joints' value
       [out] double *T: placeholder to put homogeneous transformation matrix, with length 16
     */
    void forward(const double *q, double *T);
    /*
       Inverse kinematics
       [in] const double *T: target homogenous transformation matrix with length 16
       [out] double q_sols: placeholder for solutions, with length 2*4
       [out] int: number of solutions
     */
    int inverse(const double *T, double *q_sols);
}

Python中的预期行为如下

> import arm_kinematics
> T = [0.0] * 16
> arm_kinematics.forward([0.0, 0.0, 0.0, 0.0], T)
> T
  [1.0, 0.0, 0.0, 0.6, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.139, 0.0, 0.0, 0.0, 1.0]
> q_sols = [0.0] * 8
> num_sols = arm_kinematics.inverse(T, q_sols)
> q_sols[:num_sols*4]
  [0.0, 0.0, 0.0, 0.0]

如何编写接口文件,以便将Python列表转换成C++数组,反之亦然?有没有可能让Python通过引用传递? 我发现

typemap

可以处理具有已知数组大小的函数,例如int foo(int arr[4]),但是如果现在数组通过指针传递,而我们不知道它的大小,我应该如何修改接口文件

提前感谢


Tags: 模块文件inwith数组outlengthplaceholder
1条回答
网友
1楼 · 发布于 2024-05-23 17:28:49

使用SWIG最简单的方法是使用numpy.i

将C++接口更改为

namespace ARM_KINEMATICS{
  /*
    Forward kinematics
    [in] const double *q: joints' value
    [out] double *T: placeholder to put homogeneous transformation matrix, with length 16
  */
  void forward(const double *q, const int nq, double **T, int* nT);
  /*
    Inverse kinematics
    [in] const double *T: target homogenous transformation matrix with length 16
    [out] double q_sols: placeholder for solutions, with length 2*4
    [out] int: number of solutions
  */
  int inverse(const double *T, const int nT, double **q_sols, int* nq_sols);
}

然后为SWIG创建一个工作接口

%module robot
%{
  #define SWIG_FILE_WITH_INIT
  #include "robot.h"
%}

%include "numpy.i"

%init
%{
  import_array();
%}

%apply (double* IN_ARRAY1, int DIM1) {(const double *q, const int nq)}

%apply (double* IN_ARRAY1, int DIM1) {(const double *T, const int nT)}

%apply (double** ARGOUTVIEWM_ARRAY1, int* DIM1) \
{(double** T, int* nT)}

%apply (double** ARGOUTVIEWM_ARRAY1, int* DIM1) \
{(double** q_sols, int* nq_sols)}


%include "robot.h"

如果您查看numpy.i,您将看到您也可以输入/输出矩阵

类型映射在numpy.i中定义,它与NumPy一起提供

相关问题 更多 >