无符号长*缓冲区

unsigned long * buffer

我正在尝试使用 C++ 扩展 python 以与仪器对话。但是我在指针(和缓冲区)方面遇到了一些问题。我还是 C++/C 语言的新手。

在我的 C 头文件中,我有一个函数:

long EXPORT read_output(long DeviceID, char* Buffer, unsigned long Length, unsigned long* BytesRead);

所以我在我的 Python 模块中创建了这个函数:

static PyObject *
Py_Get_ASCII(PyObject *self, PyObject *args)
{
  long DeviceID;
  char* Buffer;
  unsigned long* BytesRead;
  int param = PyArg_ParseTuple(args, "lz", &DeviceID, &Buffer);
  //something for BytesRead (dont' know)***
  long response = read_output(DeviceID, Buffer, strlen(Buffer), BytesRead);
  // * enter more code depending on value of response
  Py_INCREF(Py_None);
  return Py_None;
}

这可能很愚蠢,但我很困惑我应该如何解释 "unsigned long* BytesRead" 并为其创建缓冲区。头文件只说 BytesRead 应该代表读取的字节数,我假设这是设备读取的字节数。一切似乎都正常,除了当我尝试合并 "BytesRead." 时,我会很感激对我应该做的事情提供一些帮助。

如果read_output是要读东西的话,大概会return参数BytesRead中读取的字节数。出于这个原因 read_output 需要一个指针,指向它将存储读取的字节数的位置。然后,您必须在调用函数 Py_Get_ASCII 中将其声明为 'unsigned long BytesRead' 并将其作为“&BytesRead”传递给函数。

您不需要任何 "buffer"。

传统上你实例化一个实际的 unsigned long 然后传递一个指向它的指针:

unsigned long BytesRead = 0;
long response = read_output(DeviceID, Buffer, strlen(Buffer), &BytesRead);
//                                                            ^^^^^^^^^^

现在 BytesRead 包含读取的字节数。

这种技术被称为 out parameters,它解决了函数只能 return 一个值的限制。