Python C api

文档: https://docs.python.org/3.7/extending/extending.html
https://docs.python.org/3/extending/extending.html#calling-python-functions-from-c
- Python到C
可以使用 PyArg_Parse 或 PyArg_ParseTuple 或 PyArg_ParseTupleAndKeywords

PyArg_ParseTuple(args, ""); //无参数,调用 f()
PyArg_ParseTuple(args, "s", &s); // 字符串参数,比如调用f('hello')
PyArg_ParseTuple(args, "lls", &k, &l, &s); //f(1, 2, 'three')
PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);// f((1, 2), 'three')
PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);// f('a') f('a', 'w') f('a', 'wb', 100)
  • C到python
    使用 Py_BuildValue 或 专用的 PyString_FromString一类
Py_BuildValue("s", "hello")              'hello'
Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
Py_BuildValue("s#", "hello", 4)          'hell'
Py_BuildValue("()")                      ()
Py_BuildValue("(i)", 123)                (123,)
Py_BuildValue("(ii)", 123, 456)          (123, 456)
Py_BuildValue("(i,i)", 123, 456)         (123, 456)
Py_BuildValue("[i,i]", 123, 456)         [123, 456]
Py_BuildValue("{s:i,s:i}","abc", 123, "def", 456)    {'abc': 123, 'def': 456}

Python C api_第1张图片

你可能感兴趣的:(python,C)