我编写了一个C++模块来计算我的SCARA机器人手臂的正运动学和逆运动学,我想将这个模块封装到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?我发现
类型图
可以处理具有已知数组大小的函数,例如int foo(int arr[4]),但是如果现在数组是通过指针传递的,而我们不知道它的大小,我应该如何修改接口文件?
提前感谢!
发布于 2021-02-21 22:59:38
使用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一起提供。
https://stackoverflow.com/questions/66296634
复制相似问题