使用 ctypes 在 python 中调用 C 函数

Calling C functions in python with ctypes

我有一个 C 代码,我想在 python 中使用 ctypes。

int read_mesh(int *node,char *buf,int bufsize,int exitflag,int timeoutms)
  {
  int ndevice,locnode,retval;
 
  locnode = FROM_MESH;
  retval = readserial(&locnode,buf,bufsize,0,(exitflag & 3),timeoutms);

  if(locnode == 0)
    *node = 0;
  else
    *node = dev[locnode]->node;  // known sender
   
  return(retval);
  }

我正在尝试使用 ctypes 调用它,但我现在卡住了,无法 运行。这是我的代码,但我认为前两个参数有问题。

bt = ctypes.CDLL("functions.so")
bt.read_mesh.argtypes = (ctypes.POINTER(ctypes.c_int),ctypes.POINTER(ctypes.c_char),ctypes.c_int,ctypes.c_int,ctypes.c_int)

node = None
arrSv = ctypes.c_char * 32
bt.read_mesh(node,arrSv(*[b"0"]*32),ctypes.sizeof(arrSv),2,0)

在 C 中,它是这样调用的。

int nread,node;
char inbuf[32];
read_mesh(&node,inbuf,sizeof(inbuf),2,0);

我陷入了前两个论点。请帮我解决一下这个。非常感谢!

代码需要为输出参数传递一个ctypes兼容对象的地址。当前 None 被传递给 node ,这相当于一个 C 空指针。这是一个工作示例:

test.c

#include <memory.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API int read_mesh(int *node, char *buf, int bufsize, int exitflag, int timeoutms)
{
    // sample output values
    *node = 123;
    memset(buf, 'A', bufsize);
    return 1;
}

test.py

import ctypes as ct

dll = ct.CDLL('./test')
dll.read_mesh.argtypes = ct.POINTER(ct.c_int), ct.c_char_p, ct.c_int, ct.c_int, ct.c_int
dll.read_mesh.restype = ct.c_int

node = ct.c_int()        # a ctypes-compatible int
buf = (ct.c_char * 32)() # a ctypes-compatible char[32]
# ctypes.byref() is equivalent to C & (take the address of).
# len() gives elements of array, ctypes.sizeof() gives number of bytes.
# Same in this case, but different answer for, say, (c_int * 5)().
dll.read_mesh(ct.byref(node), buf, len(buf), 2, 0)
print(f'{node.value=}')
print(f'{buf.raw=}')

输出:

node.value=123
buf.raw=b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'