如何编写基于 C 的模块来处理 python 字典?
How do I write a C-based module to process python dictionaries?
我最近需要为群聊机器人编写一个模块,该模块可以响应每条消息并查找是否有与关键字匹配的内容。机器人本身基于 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 与这本词典一起工作。这里需要用到什么样的数据结构?
首先你需要为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)
希望这是clear.you需要根据您的需要修改。
我最近需要为群聊机器人编写一个模块,该模块可以响应每条消息并查找是否有与关键字匹配的内容。机器人本身基于 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 与这本词典一起工作。这里需要用到什么样的数据结构?
首先你需要为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)
希望这是clear.you需要根据您的需要修改。