Extension build link error

garyr garyr at fidalgo.net
Wed Aug 12 18:08:18 CEST 2015


I'm trying to build an extension module and was having problems so I decided
to try something simpler. Article 16.5, "Coding the Methods of a Python
Class in C" in the first edition of the Python Cookbook looked about right.
I generated the code and a setup.py file (shown below). When I run

python setup.py build_ext --inplace

I get the following errors:

LINK : error LNK2001: unresolved external symbol init_Foo
build\temp.win32-2.7\Release\_Foo.lib : fatal error LNK1120: 1 unresolved
externals

If I change the name of the initialization function from Foo_init (as in the
book) to init_Foo the build succeeds but import _Foo fails:

    import _Foo
SystemError: dynamic module not initialized properly

This is the problem I was having with the extension module I was trying to 
write.
What can I do to correct this?

I'm using Python 2.7 on Win XP.
==========================================================
# File: setup.py

from setuptools import setup, Extension
setup(name='Foo',
    version='0.1',
    ext_modules=[Extension('_Foo', ['Foo.c'],
    include_dirs=['C:\Program Files\Common Files\Microsoft\Visual C++ for
Python\9.0\VC\include',
                'C:\Miniconda\include'],
                    )],
    )
=================================================
# File: Foo.c

#include <Python.h>
PyObject* init_Foo(PyObject *self, PyObject *args){
    printf("Foo.__init__ called\n");
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject* Foo_doSomething(PyObject *self, PyObject *args){
    printf("Foo.doSomething called\n");
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef FooMethods[] = {
    {"__init__",        init_Foo,             METH_VARARGS, "doc_string"},
    {"doSomething", Foo_doSomething, METH_VARARGS, "doc string"},
    {0, 0},
};

static PyMethodDef ModuleMethods[] = {{0,0}};

void initFoo() {
PyMethodDef *def;

    PyObject *module = Py_InitModule("Foo", ModuleMethods);
    PyObject *moduleDict = PyModule_GetDict(module);
    PyObject *classDict = PyDict_New();
    PyObject *className = PyString_FromString("Foo");
    PyObject *fooClass = PyClass_New(NULL, classDict, className);
    PyDict_SetItemString(moduleDict, "Foo", fooClass);
    Py_DECREF(classDict);
    Py_DECREF(className);
    Py_DECREF(fooClass);
    for (def = FooMethods; def->ml_name != NULL; def++)     {
        PyObject *func = PyCFunction_New(def, NULL);
        PyObject *method = PyMethod_New(func, NULL, fooClass);
        PyDict_SetItemString(classDict, def->ml_name, method);
        Py_DECREF(func);
        Py_DECREF(method);
    }
}







More information about the Python-list mailing list