gpt4 book ai didi

python - C++ DLL 返回一个从 Python 调用的指针

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:25 26 4
gpt4 key购买 nike

我正在尝试从 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) 正确打印

关于python - C++ DLL 返回一个从 Python 调用的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38513929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com