Python ctypes:byref() 未反映更新后的值

Python ctypes : byref() is not reflecting the updated value

我正在为 python 中的某些 C API 编写包装程序。我能够编写包装器,当我试图从另一个程序调用该包装器以访问 API 时,指针变量更改的值未在 python 变量中更新。

我的 API 代码来自 pythonWrapper.py :

import ctypes
from enum import Enum

_obj = cdll.LoadLibrary(./sharedObj.so)

#some enums and structure will be here like :

class structwrap(Structure):
  _fields_ = [("id", c_int),
              ("type", c_int),
              ("state", c_int)]
  def __init__(self):
      self.id = 0
      self.type = 0
      self.state = 0


def wrappedAPI(structwrapList, count):
    _obj.wrappedAPI.argtypes = [ctypes.POINTER(structwrapList),ctypes.POINTER(c_int)]
    _obj.wrappedAPI.restype = int
    if not structwrapList:
        structwrapList = structwrap()
    ret = _obj.orgAPI(byref(structwrapList),byref(c_int(count)))
    print (count)
    return ret

对应的C代码为:

typedef struct structOrg
{
    int                 id;     /* index */
    dvDevIcType_t       type;  /* type */
    dvDevExecState_t    state;   /* state */
}structOrg_t;


int orgAPI(structOrg_t *structList, int *count){
...
//count value is being changed here. like count = count+1
}

正在从 test.py 调用上述 python 文件:

from ctypes import *
from  pythonWrapper import *
count =0
ret = dvDeviceGet(None, count)
print (count)

输出 ret 成功但计数值仍然是 0 但在 c 函数中它正在被更改为 2。但在 python 变量中它仍然是 0。

有人可以指出我的错误吗?

byref(c_int(count)) 创建一个新的 c_int 并将指针传递给 thatcount 不受影响。 count 是普通的 Python int,不是 C int 或 C int 的包装对象。

一点重构:

_obj = cdll.LoadLibrary(./sharedObj.so)

# Only need to do this once, not every time inside the function
_obj.wrappedAPI.argtypes = [ctypes.POINTER(structwrapList),ctypes.POINTER(c_int)]
_obj.wrappedAPI.restype = ctypes.c_int # Needs to be a ctypes type.

def wrappedAPI(structwrapList,count):
    if not structwrapList:
        structwrapList = structwrap()
    c_count = ctypes.c_int(count) # Create a ctypes type to pass by reference
    ret = _obj.orgAPI(byref(structwrapList),ctypes.byref(c_count))
    return ret,c_count.value

通话方式:

ret,count = dvDeviceGet(None, count)