【问题标题】:How do I write a C-based module to process python dictionaries?如何编写基于 C 的模块来处理 python 字典?
【发布时间】:2019-05-27 04:50:10
【问题描述】:

我最近需要为群聊机器人编写一个模块,该模块可以响应每条消息并查找是否有任何与关键字匹配的内容。机器人本身基于 Python 并提供 Python API。由于业务需要,我可能想用C语言编写这个程序,所以像这样:

import my_c_module

DICTIONARY = {} # nested dictionary containing keywords, replies, modes, group context etc

async def respond_to_mesg():
    ....
    invokes the c function
    ....

c 函数需要处理消息和字典并查看匹配项。

让我感到困惑的主要部分是我不知道如何让 C 与这本字典一起工作。这里需要使用什么样的数据结构?

【问题讨论】:

标签: python c hashtable


【解决方案1】:

首先你需要为c文件生成一个共享库。假设文件名为 library.c,它具有函数 myfunction。

int myFunction(int num) 
{ 
    if (num == 0) 

        // if number is 0, do not perform any operation. 
        return 0; 
    else
        // if number is power of 2, return 1 else return 0 

    num & (num - 1) == 0 ? return 1 : return 0 
}

您可以使用以下命令编译上述c文件library.c。

cc -fPIC -shared -o dicmodule.so library.c

以上语句将生成一个名为 dicmodule.so 的共享库。现在,让我们看看如何在 python 中使用它。在 python 中,我们有一个名为 ctypes 的库。使用这个库,我们可以在 python 中使用 C 函数。

import ctypes 
NUM = 16      
# dicmodule loaded to the python file 
# using fun.myFunction(), 
# C function can be accessed 
# but type of argument is the problem. 

fun = ctype.CDLL(dicmodule.so)   
# Now whenever argument  
# will be passed to the function                                                         
# ctypes will check it. 

fun.myFunction.argtypes(ctypes.c_int) 

# now we can call this  
# function using instant (fun) 
# returnValue is the value  
# return by function written in C  
# code 
returnVale = fun.myFunction(NUM)

希望这很清楚。您需要根据需要进行修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2021-10-23
    相关资源
    最近更新 更多