首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将C++卷到Python中

将C++卷到Python中
EN

Stack Overflow用户
提问于 2021-02-20 21:15:38
回答 1查看 78关注 0票数 0

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

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

代码语言:javascript
复制
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中的预期行为如下

代码语言:javascript
复制
> 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?我发现

类型图

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

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-21 22:59:38

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

将您的C++接口更改为

代码语言:javascript
复制
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提供一个工作接口。

代码语言:javascript
复制
%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一起提供。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66296634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档