cythonbook / examples

Code examples from the book.
425 stars 157 forks source link

Example 3 in Chapter 1 does not work in Python 3.x? #4

Open geoalchimista opened 7 years ago

geoalchimista commented 7 years ago

When timing the Python/C API extension example in 01-essentials/03-timings/, I got an error like this

ImportError: dlopen( ./examples/01-essentials/03-timings/cfib.cpython-36m-darwin.so, 2): Symbol not found: _Py_InitModule
  Referenced from: ./examples/01-essentials/03-timings/cfib.cpython-36m-darwin.so
  Expected in: flat namespace
 in ./examples/01-essentials/03-timings/cfib.cpython-36m-darwin.so

The error is from line 14 in 01-essentials/03-timings/timings.py

cexttime_0 = timer(0, N, name='fib', module='cfib')

I found that Python 3.x no longer uses Py_InitModule. So this part would not work.


Here's my attempt to fix the 01-essentials/03-timings/cfib_wrap.c for Python 3.x.

The original PyMODINIT_FUNC block

PyMODINIT_FUNC
initcfib(void)
{
    (void) Py_InitModule("cfib", funcs);
}

can be replaced with

static struct PyModuleDef fib =
{
    PyModuleDef_HEAD_INIT,
    "fib",
    "",
    -1,
    funcs
};

PyMODINIT_FUNC PyInit_cfib(void) {
    return PyModule_Create(&fib);
}

This should make the example 01-essentials/03-timings to run in Python 3.x.

pydojo commented 4 years ago

hi @geoalchimista , I am learning this courses, can you tell me &fib what is doing?

pydojo commented 4 years ago

hi @geoalchimista , I am learning this courses, can you tell me &fib what is doing?

In Chapter3 has introduced, see about dereference pointer section.😊