Search code examples
c++crobotframework

How to integrate C++ APIs in Robot framework?


I have developed C++ APIs for my project. Also created a linux .so shared library from this. I need to call these APIs using robot framework keywords.

Thanks in advance.


Solution

  • C++ APIs can be easily called using python library ctypes. As you might already know python libraries can be integrated in robot framework.

    Let's say you have to call SendMesg C++ API using robot framework. Please follow following steps:

    1. Creating C++ APIs library .so file

    connect.cpp

    extern "C"
    {
    
       int Initialize(char* ip, int port)
       {
           //creates socket connection with remote host
       }
    
       int SendMesg(char* msg)
       {
          //Send mesg code
       }
    }
    

    g++ -std=c++11 -fpic -c connect.cpp

    g++ -std=c++11 -shared -g -o connect.so connect.o

    Now you have created connect.so shared library in the same path as your cpp file.

    2. Creating python wrapper for C++ APIs

    connectWrapper.py

    import ctypes
    
    class connectWrapper:
    
    def __init__(self, ip , port):
        self.Lib = ctypes.cdll.LoadLibrary('absolute path to connect.so')
        self.Lib.Initialize.argtypes = [ctypes.c_char_p, ctypes.c_int]
        self.Lib.Initialize(ip, port)
    
    def SendMessageWrapper(self, msg):
        self.Lib.SendMesg.argtypes = [ctypes.c_char_p]
        print self.Lib.SendMesg(msg)
    

    4 things to remember while creating python wrapper APIs.

    a) python file name is same as class name

    b) While calling APIs using ctypes you should always specify the input parameter types. Otherwise you may get the following error while running robot file using this python library:

    NotImplementedError: variadic functions not supported yet; specify a parameter list

    In this case, we had specified parameters as ctypes.c_char_p for string types and ctypes.c_int as integer. For more information you may use follow:

    [http://python.net/crew/theller/ctypes/tutorial.html#specifying-the-required-argument-types-function-prototypes][1]

    c) Absolute path to connect.so is given in ctypes.cdll.LoadLibrary API.

    d) Set the python file to executable by using chmod +x connectWrapper.py

    3. Adding python library to robot file

    test.robot.txt

    ** * Settings * **
    
    Library    "absoulte path to connectWrapper.py" 10.250.0.1    8080
    
    ** * Test Cases * **
    
    Send Message
    
            SendMessageWrapper "Hello World"
    

    As you may notice, python library is added in the settings section with arguments passed as IP and port. We have added SendMessage keyword in test cases section with the string message "Hello World" as input argument.

    I hope after running the command :

    robot test.robot.txt

    everything works fine :)