python - 从 Python 使用 C

标签 python c ctypes network-interface

我想知道来自 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 的步骤是什么?我该怎么做?还有没有办法返回元组列表而不是打印它?我需要编译它吗?如果我能怎么办?

最佳答案

Is this good?

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

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

您编写的内容不需要 ctypes,因为它是用 C 编写的实际 Python 模块。在将代码编译为 interfaces.pyd 后使用 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?

与正常listtuple功能;创建对象并根据需要依次设置每个元素。

关于python - 从 Python 使用 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30382558/

相关文章:

c - 为嵌套循环声明虚拟变量的更好方法是什么?

python - 带索引恢复的 QListView

python - 将 KeyboardMaestro 的变量传递给 Python 脚本

c无效的主要功能?返回 16 值

mysql - c 上的 const char 具有相同的变量但不同的值

python - ctypes c_char_p 的不同行为?

python - Flask 应用程序在 60 秒空闲时间后返回 "MySQL server has gone away"

python - 求两个三位数的最大回文积 : what is the error in logic?

python - ctype在代码中没有发现属性错误

具有灵活数组成员的 Python ctypes 结构到 bytearray