Page 81
example.c
This is the combined code from the chapter - the json files are as for example given ealier
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *retInt(PyObject *self, PyObject *args)
{
int value = -1;
return Py_BuildValue("I", value);
}
static PyObject *strTostr(PyObject *self, PyObject *args)
{
char *name = "Brian";
return Py_BuildValue("s", name);
}
static PyObject *strTostr2(PyObject *self, PyObject *args)
{
char name[] = " Brian";
name[0] = 0xCE;
name[1] = 0x94;
return Py_BuildValue("s", name);
}
static PyObject *strTostrLen(PyObject *self, PyObject *args)
{
char name[] = " Brian";
Py_ssize_t len = 5;
name[0] = 0xCE;
name[1] = 0x94;
return Py_BuildValue("s#", name, len);
}
static PyObject *strTobytesLen(PyObject *self, PyObject *args)
{
char name[] = " Brian";
Py_ssize_t len = 5;
name[0] = 0xCE;
name[1] = 0x94;
return Py_BuildValue("y#", name, len);
}
static PyObject *wcharTostrLen(PyObject *self, PyObject *args)
{
wchar_t name[] = L" Brian";
Py_ssize_t len = 5;
name[0] = 0x0394;
return Py_BuildValue("u#", name, len);
}
static PyObject *wcharTostrLen2(PyObject *self, PyObject *args)
{
wchar_t name[] = L" Brian";
Py_ssize_t len = 5;
name[0] = 0xD83E;
name[1] = 0xDD10;
return Py_BuildValue("u#", name, len);
}
static PyObject *retTuple(PyObject *self, PyObject *args)
{
int number = 42;
double x = 1.2, y = 1.1;
char *name = "brian";
return Py_BuildValue("(isdd)", number, name, x, y);
}
static PyObject *retList(PyObject *self, PyObject *args)
{
int number = 42;
double x = 1.2, y = 1.1;
char *name = "brian";
return Py_BuildValue("[isdd]", number, name, x, y);
}
static PyObject *retDict(PyObject *self, PyObject *args)
{
int number = 42;
double x = 1.2, y = 1.1;
char *name = "brian";
return Py_BuildValue("{sisssdsd}", "first", number,"second", name,"x", x,"y", y);
}
static PyMethodDef AddMethods[] = {
{"retInt", retInt, METH_VARARGS, "an example"},
{"strTostr", strTostr, METH_VARARGS, "an example"},
{"strTostr2", strTostr2, METH_VARARGS, "an example"},
{"strTostrLen", strTostrLen, METH_VARARGS, "an example"},
{"strTobytesLen", strTobytesLen, METH_VARARGS, "an example"},
{"wcharTostrLen", wcharTostrLen, METH_VARARGS, "an example"},
{"wcharTostrLen2", wcharTostrLen2, METH_VARARGS, "an example"},
{"retTuple", retTuple, METH_VARARGS, "an example"},
{"retList", retList, METH_VARARGS, "an example"},
{"retDict", retDict, METH_VARARGS, "an example"},
{NULL, NULL, 0, NULL} // sentinel
};
static struct PyModuleDef addmodule = {
PyModuleDef_HEAD_INIT,
"example",
"C library to test API",
-1,
AddMethods};
PyMODINIT_FUNC PyInit_example(void)
{
return PyModule_Create(&addmodule);
}
test.py
import example
print(example.retInt())
print(example.strTostr())
print(example.strTostr2())
print(example.strTostrLen())
print(example.strTobytesLen())
print(example.wcharTostrLen())
#print(example.wcharTostrLen2())
print(example.retTuple())
print(example.retList())
print(example.retDict())
print("end")