从Python调用C DLL函数时出错

问题描述 投票:0回答:1

我正在尝试执行必须调用C函数的Python代码,该函数执行一些计算并将值保存在必须可从Python代码访问的指针中。我想这样做是因为我正在构建一个DLL,并且我想验证DLL函数中的代数,因此我想使用python代码来验证DLL。Python代码

from ctypes import *


if __name__ == '__main__':

    mydll = cdll.LoadLibrary("./dll_simples.dll")
    funcao = mydll.simuser
    funcao.argtypes = c_double,c_double,POINTER(c_double),POINTER(c_double)



    a = 0
    b = 0
    input_1 = (c_double * 1)()
    input_1[0] = 5
    output_1  = (c_double * 1)()
    funcao(a,b,input_1,output_1)

和我的DLL

__declspec(dllexport) void simuser(double t, double delt, double* in, double* out)
{



out[0] = 2 * in[0];



}

执行此代码后,出现错误

funcao(a,b,input_1,output_1)

OSError: exception: access violation reading 0x0000000000000018
python c dll ctypes
1个回答
0
投票

列出[Python 3.Docs]: ctypes - A foreign function library for Python

因此,您希望将数组传递给需要指针的函数。在这种情况下,需要ctypes.cast

funcao(a, b, cast(input_1, POINTER(c_double)), cast(output_1, POINTER(c_double)))

一个工作示例:[SO]: Pointer from Python (ctypes) to C to save function output (@CristiFati's answer)

© www.soinside.com 2019 - 2024. All rights reserved.