使用 Python 中的 C

Using C from Python

我想知道来自 python 的 NetworkInterfaces 的名称,但似乎不可能来自 python 所以我使用这个 C 代码:

#include <Python.h>
#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>

#pragma comment(lib, "iphlpapi.lib")

PyObject* GetInterfaces (PyObject* self){
    ULONG buflen = sizeof(IP_ADAPTER_INFO);
    IP_ADAPTER_INFO *pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);

    if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);
    }

    if (GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) {
        for (IP_ADAPTER_INFO *pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) {
            printf("%s (%s)\n", pAdapter->IpAddressList.IpAddress.String, pAdapter->Description);
        }
    }

    if (pAdapterInfo) free(pAdapterInfo);
    return 0;
}

static char interfaces_docs[] =
    "GetInterfaces( ): prints the interfaces name and IP\n";

static PyMethodDef interfaces_funcs[] = {
    {"GetInterfaces", (PyCFunction)GetInterfaces, 
     METH_NOARGS, interfaces_docs},
    {NULL}
};

void initinterfaces(void)
{
    Py_InitModule3("interfaces", interfaces_funcs,
                   "Interfaces Module");
}

这样好吗?使用 ctypes 将其导入 Python 的步骤是什么?我该怎么做?还有一种方法可以 return 元组列表而不是打印它吗?我需要编译它吗?如果我能怎么办?

Is this good?

差不多。永远不要 return 0/null 作为 PyObject* 除非你是 signaling an exception;而是增加 Py_None 和 return 它。您可能还想添加实际的错误检查代码。

And what are the steps to importing it into Python with ctypes? How can I do it?

您编写的内容不需要 ctypes,因为它是用 C 编写的实际 Python 模块。将代码编译为 interfaces.pyd.[=18 后使用 import interfaces =]

Also is there a way to return a list of tuples instead of printing it? Do I need to compile it? If I do how can I?

具有正常的list and tuple功能;创建对象并根据需要依次设置每个元素。