C API type issue

Rich Henry againstmethod at gmail.com
Fri Oct 3 17:27:50 CEST 2008


Made a simple little test program as im learning to embed python, have a
simple script that just sets x=10.0 in test.py and prints type(x). Python
prints that x is a float but PyFloat_Check() returns false. If i removed the
check and just force it to print the double value, its correct. Any ideas
why PyFloat_Check() returns false on a float? Thanks in advance.

#include "Python.h"
#include <cstdio>

int main(int argc, char** argv)
{
    FILE* fp = fopen("test.py", "r");
    assert(fp);

    Py_Initialize();

    //
    //    create a dictionary, load the builtins and execute our file
    //
    PyObject *d = PyDict_New();
    assert(d);
    PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
    PyRun_File(fp, "test.py", Py_file_input, d, NULL);

    //
    //    get a variable that should be in our global namespace
    //
    PyObject *x = PyDict_GetItemString(d, "x");
    assert(x);

    Py_DECREF(d);

    //
    //    determine its type and print it
    //
    if(PyFloat_Check(x))
    {
        printf("x = %lf\n", PyFloat_AS_DOUBLE(x));
    }

    Py_DECREF(x);

    Py_Finalize();
    fclose(fp);
    return 0;
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081003/5d52f14e/attachment.html>


More information about the Python-list mailing list