C++DLL返回从Python调用的指针
C++ DLL returning a pointer called from Python
我正试图从python访问C++dll(我是python新手)。我克服了许多调用约定问题,最终使它在没有任何编译/链接错误的情况下运行。然而,当我在python中打印从C++dll返回的数组时,它显示了所有随机初始化的值。看起来这些值没有正确返回。
我的C++代码是这样的。
double DLL_EXPORT __cdecl *function1(int arg1, int arg2, double arg3[],int arg4,double arg5,double arg6,double arg7, double arg8)
{
double *Areas = new double[7];
....Calculations
return Areas;
}
我的python代码如下:
import ctypes
CalcDll = ctypes.CDLL("CalcRoutines.dll")
arg3_py=(ctypes.c_double*15)(1.926,1.0383,0.00008,0.00102435,0.0101,0.0,0.002,0.0254,102,1,0.001046153,0.001046153,0.001046153,0.001046153,20)
dummy = ctypes.c_double(0.0)
CalcDll.function1.restype = ctypes.c_double*7
Areas = CalcDll.function1(ctypes.c_int(1),ctypes.c_int(6),arg3_py,ctypes.c_int(0),dummy,dummy,dummy,dummy)
for num in HxAreas:
print("t", num)
打印语句的输出如下:
2.4768722583947873e-306
3.252195577561737e+202
2.559357001198207e-306
5e-324
2.560791130833573e-306
3e-323
2.5621383435212475e-306
任何关于我做错了什么的建议都将不胜感激。
而不是
CalcDll.function1.restype = ctypes.c_double * 7
应该有
CalcDll.function1.restype = ctypes.POINTER(ctypes.c_double)
然后
Areas = CalcDll.function1(ctypes.c_int(1), ctypes.c_int(6), arg3_py,
ctypes.c_int(0), dummy, dummy, dummy, dummy)
for i in range(7):
print("t", Areas[i])
我不确定ctypes在"ctypes.c_double*7"的情况下会做什么,如果它试图从堆栈中提取七个double或什么。
测试
double * function1(int arg1, int arg2, double arg3[],
int arg4, double arg5, double arg6,
double arg7, double arg8)
{
double * areas = malloc(sizeof(double) * 7);
int i;
for(i=0; i<7; i++) {
areas[i] = i;
}
return areas;
}
使用restype = ctypes.POINTER(ctypes.c_double)
正确打印数组中的值
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 当使用通配符和null指针调用函数时,对输出的说明
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 使用基类指针调用基类的值构造函数的语法是什么?
- 是否可以使用函数指针调用虚拟析构函数?
- 使用C++指针调用 python 函数
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 从带有参数的基函数指针调用基方法
- 使用唯一指针调用函数会使我的程序崩溃
- C++::在构造函数退出之前通过指针调用成员函数
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 什么时候用指针调用C++类构造函数
- C++ - 使用变量指针调用函数
- 为什么我可以通过野生指针调用成员函数
- 从指针调用方法时出现分段错误
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- C++ abort() 在函数内的抽象类对象指针调用上