Search code examples
pythonchashtable

How do I write a C-based module to process python dictionaries?


I recently need to write a module for a group chat bot that responds to every single message and find if there is anything that matches the keywords. The robot itself is based on Python and provides python APIs. Due to the need of business I may want to write this procedure in C language, so like this:

import my_c_module

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

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

the c function needs to process the message and dictionary and see matches.

The main part that confuses me is that I do not know how to get C to work with this dictionary. What kind of data structure needs to be used here?


Solution

  • First you need to generate a shared library for the c file. Let's say the file name is library.c which has the function 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 
    }
    

    You can compile the above c file library.c using the following command.

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

    Above statement will generate a shared library with name dicmodule.so. Now, let’s see how to make use of it in python. In python, we have one library called ctypes. Using this library we can use C function in python.

    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)
    

    Hope this is clear.you need to modify this according to your needs.