简体   繁体   中英

A simple Python extension in C

I am trying to create a simple python extension module. I compiled the following code into a 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 obtain an error message

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

What's wrong with my code?

I'm guessing that it has to do with using a keyword as a function name. I tried defining a function print() in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.

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