错误描述
我在用python的ctypes库调用c++的.so文件时候,出现了下面的错误:
ctypes.ArgumentError: argument 2: <type 'exceptions.TypeError'>: Don't know how to convert parameter 2
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020012113054376.png)
下面对我遇到这个问题时的情况做一下说明:
C++源文件中的函数需要传入的第二个参数是double型:
double a_mov(int ctrl, double pos_x, double pos_y){
a._pos._x = pos_x;
a._pos._y = pos_y;
a._pos._x = op_pos_x;
a._pos._y = op_pos_y;
a0.cal_next_pos(b0._pos, des_pos, W_O, W_T, W_D, W_C, P_O, P_T, P_D, P_C);
if(ctrl == 0)
return a0._next_pos._x;
else
return a0._next_pos._y;
}
python程序:
在调用之前,我先用下面的程序(注释1处)将函数返回类型设置为c_double
并在(注释2处)将变量last_a_x,last_a_y设置为c_double类型,
运行结果是:只成功输出了一次,输出第二次时出现了错误
按理说,a_x变量(注释3处)的类型应该是c_double,但是我输出它的类型进行测试(注释4处)时发现,它的类型是float:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200121132851976.png)
也即是说,(注释1处)的修改只是将函数的返回类型修改为了ctypes里的c_double,在python对应为float类型。(c、ctypes和python之间的对应关系详见参考资料【2】)
from ctypes import *
pos = CDLL('./angleStreategy.so')
pos.init()
a_mov = pos.a_mov
a_mov.restype = c_double #----------1
last_a_x = c_double(0.0)
last_a_y = c_double(0.0) #----------2
for i in range(0,10):
a_x = pos.a_mov(0,last_a_x,last_a_y)
a_y = pos.a_mov(1,last_a_x,last_a_y) #----------3
print(type(a_x)) #-----------4
last_a_x = a_x
last_a_y = a_y #----------5
print(a_x)
print(a_y)
解决方法
将(注释5处)修改为
last_a_x = c_double(a_x)
last_a_y = c_double(a_y)
问题解决!
(问题比较特殊,所以说的比较详细,这样才有参考价值
参考资料:
【1】python调用c/c++代码以及解决ctypes.ArgumentError: argument 1: class ‘TypeError’: Don’t know how to convert
【2】python中运用ctypes库实现c风格变量的定义和调用