Skip to content

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

@geoalchimista

Description

@geoalchimista

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions