Simple Python extension in C

I am trying to create a simple python extension module. I compiled the following code in the transit.so dynamic module

#include <python2.6/Python.h>

static PyObject*
_print(PyObject* self, PyObject* args)
{
    return Py_BuildValue("i", 10);
}

static PyMethodDef TransitMethods[] = {
    {"print", _print, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittransit(void)
{
    Py_InitModule("transit", TransitMethods);
}

However, trying to call this from python

import transit
transit.print()

I get an error

  File "test.py", line 2
    transit.print()
                ^
SyntaxError: invalid syntax

What is wrong with my code?

+3
source share
1 answer

I assume this is due to using the keyword as the name of the function. I tried to define a function print()in the module just now for testing and received the same error. Try changing the name of this function a bit and see if it fixes the problem.

+4
source

Source: https://habr.com/ru/post/1750230/


All Articles