Search code examples
pythoncctypesprogram-entry-pointargv

Calling arguments from main() in C from Python with ctypes


I'm trying to call a main() from open-plc-utils/slac/evse.c via ctypes. Therefor I turned the c file into a shared object (.so) and called it from Python.

from ctypes import *

so_file = "/home/evse/open-plc-utils/slac/evse.so"

evse = CDLL(so_file)

evse.main.restype = c_int
evse.main.argtypes = c_int,POINTER(c_char_p)
args = (c_char_p * 1)(b'd')
evse.main(len(args),args)

The d should return debug output but the output in the stdout is the same no matter which letter I pass to main(). Do you know what I did wrong here? And how can I pass something like

evse -i eth1 -p evse.ini -c -d 

in one comand via ctypes?


Solution

  • Try the following. Make sure the first argument is the program name.

    from ctypes import *
    
    so_file = "/home/main/open-plc-utils/slac/main.so"
    
    evse = CDLL(so_file)
    
    evse.main.restype = c_int
    evse.main.argtypes = c_int,POINTER(c_char_p)
    
    def make_args(cmd):
        args = cmd.encode().split()
        return (c_char_p * len(args))(*args)
    
    args = make_args('main -i eth1 -p main.ini -c -d')
    evse.main(len(args), args)