简体   繁体   中英

How to pass a list ,integer,strings as an arguments of function from python to C

I have a python code as mentioned below ,its calling a "C" function trans implemenetd as python extension .How to extract integer,string,list all different type of argument together at C code ? Below code is not working to extract list as an argument .Code below is just a sample code which will give an idea about the question I have .it's not complete code .

Test.py

def tpp:  
    value =0455455  
    name ='go'  
    parameter =[0,0,0]  
    parameter[0] ='hello'
    parameter[1] ='helloworld'        
    trans(value =value, name =name ,parameter =parameter)  

trans.c

  static Pyobject mod_trans(Pyobject *self, Pyobject *args ,Pyobject *keyargs)  
   {    
     char name ;  
     int value ;  
     char* parameter;  
     static char *kwlist[] ={"value", "name", "parameter")  
     if(!PyArg_ParseTupleAndKeywords(args,keyargs, "si|items",kwlist,&name,&value,
         &parameter)  
      return NULL;


    }

You're passing in a list and expecting a string out ( char * ); this won't work. Lists can only converted to PyObject * . Therefore, you should use

PyObject *parameter;
...
if(!PyArg_ParseTupleAndKeywords(args, kwargs, "is|O", kwlist, &name, &value, &parameter))

If you want to enforce that the object is a list, use

PyObject *parameter;
...
if(!PyArg_ParseTupleAndKeywords(args, kwargs, "is|O!", kwlist, &name, &value, &PyList_Type, &parameter))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM