简体   繁体   English

Python ctypes 传递指针并获得空指针访问

[英]Python ctypes Passing a Pointer and getting null pointer access

I'm using Python and ctypes to use a .dll supplied by a company for the use with a load cell amplifier.我正在使用 Python 和 ctypes 来使用公司提供的 .dll 与称重传感器放大器一起使用。 I manage to get a reading with their software, but I can't get my Python code to work.我设法阅读了他们的软件,但我的 Python 代码无法正常工作。 The company is ME-MessSysteme , and the amplifier is the GSV-2 ( Manual Here ).该公司是ME-MessSysteme ,放大器是 GSV-2( 此处为手册)。

The company's description of the function:公司对功能的描述:

C: int GSVread ( int no, double *ad ) C: int GSVread ( int no, double *ad )

Taken from here , page 44. Sorry, but the guide is in German.取自 此处,第 44 页。抱歉,该指南是德语版。

I'm getting a response from the amplifier after the activate function, but when I use the GSVread function, I can't get the result.我在激活功能后得到放大器的响应,但是当我使用 GSVread 功能时,我无法得到结果。 I tried to pass a pointer to a double variable as I understand it returns the value to it.我试图传递一个指向双变量的指针,因为我理解它会返回值。 When I try to access the contents I get a "ValueError: NULL pointer access".当我尝试访问内容时,我收到“ValueError: NULL pointer access”。

import ctypes
ret = ctypes.POINTER(ctypes.c_double)()
print(ret)
gsv = ctypes.cdll.LoadLibrary("DLLs_SENSOLYTICS/MEGSV.dll")
print(gsv.GSVactivate(7))
print(gsv.GSVstartTransmit(7))
print(gsv.GSVread(7, ret))
print(ret.contents)

7 indicating the COM port number. 7 表示 COM 端口号。

Thank you all in advance!谢谢大家!

****UPDATE***** Following on Dan's answer, the code that works is below: ****更新***** 按照丹的回答,有效的代码如下:

    d = ctypes.c_double()
    ret = ctypes.byref(d)

    gsv = ctypes.cdll.LoadLibrary("DLLs_SENSOLYTICS/MEGSV.dll")
    print(gsv.GSVactivate(7, ctypes.c_long(256)))
    gsv.GSVflushBuffer(7)
    print(gsv.GSVstartTransmit(7))
    time.sleep(1)
    gsv.GSVread(7, ret)
    print(d)

You need to create two objects one the double and the other the pointer to the double:您需要创建两个对象,一个是 double,另一个是指向 double 的指针:

>>> d = ctypes.c_double()
>>> ret = ctypes.pointer(d)
>>> ret.contents
c_double(0.0)

This can also be written as:这也可以写成:

ret = ctypes.pointer(ctypes.c_double())

Which is oddly similar to:这奇怪地类似于:

ret = ctypes.POINTER(ctypes.c_double)()

The documentation states that ctypes.byref is a faster ctypes.pointer that doesn't actually allocate a real ctypes.pointer object so it can only be used to be be passed to a reference as an argument to a C function.文档指出ctypes.byref是一个更快的ctypes.pointer ,它实际上并没有分配真正的ctypes.pointer对象,因此它只能用于作为 C 函数的参数传递给引用。

To use it one has to keep a direct reference to the double to be able to access the result as ctypes.byref objects do not have a contents property.要使用它,必须保持对 double 的直接引用才能访问结果,因为ctypes.byref对象没有内容属性。

d = ctypes.c_double()
ret = ctypes.byref(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM