escribió:
Made a simple little test program as im learning to embed python, have aYou got the reference count wrong. This is by far the most common source
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.
of errors when writting C code for Python (at least for beginners)
#include "Python.h"Instead of a bare dictionary, I'd use a module. Or the __main__ module.
#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);
See how PyRun_SimpleFileExFlags handles this (or just use that function,
or other variant).
//This returns a borrowed reference, not a new one.
// get a variable that should be in our global namespace
//
PyObject *x = PyDict_GetItemString(d, "x");
assert(x);
Py_DECREF(d);This releases the only reference to d, and the dictionary is deleted. This
in turn releases the last refrence to x, and it's deleted too.
// determine its type and print itAt this stage x is an invalid object.
//
if(PyFloat_Check(x))
{
printf("x = %lf\n", PyFloat_AS_DOUBLE(x));
}
Py_DECREF(x);And this is wrong now.
>
Py_Finalize();
fclose(fp);
return 0;
}
--
Gabriel Genellina