Calling Python from C

Started by
5 comments, last by Cromulent 15 years, 9 months ago
I'm trying to include a Python module in my C program and thought I would write a very simple Hello World Python script to test it out. Unfortunately this code does not seem to work. There also seems to be very little in the way of documentation on the specifics. I have read the page regarding this subject on python.org but have not found any sufficient information regarding the problem. Here is the C code:
PyObject *module, *dict, *func, *value;
Py_Initialize();
module = PyImport_ImportModule("logic");
dict = PyModule_GetDict(module);
func = PyDict_GetItemString(dict, "logic");
value = PyObject_CallFunction(func, "HW", "");
	
Py_DECREF(module);
Py_DECREF(dict);
Py_DECREF(func);
Py_DECREF(value);
	
Py_Finalize();
And the Python code:
def HW():
   print 'Hello World!'
Advertisement
I think it should be:

func=PyDict_GetItemString(dict,"HW");//get the object(function) named "HW"
value=PyObject_CallFunction(func,"");//call the function, with 0 arguments

I suggest you use boost::python though, it makes things a lot more easier, and there's pretty good documentation for it.
Quote:Original post by mikeman
I suggest you use boost::python though, it makes things a lot more easier, and there's pretty good documentation for it.


The only problem with that is Boost is a C++ library and I am using C.

Thanks for the help although unfortunately after a little closer examination it seems to be crashing on the call to PyModule_GetDict. No idea why though.
You're not checking any return values. Put proper error handling in, and see how that goes.
Quote:Original post by Kylotan
You're not checking any return values. Put proper error handling in, and see how that goes.


Sorry for the late reply. I've got it working when compiling on the command line but unfortunately it does not work from within Xcode. I guess I'll have to have another look at it to see what the IDE is doing.

Does anyone use Xcode and embed Python modules with C/C++ that could give some advice?
Quote:Original post by Cromulent
Sorry for the late reply. I've got it working when compiling on the command line but unfortunately it does not work from within Xcode. I guess I'll have to have another look at it to see what the IDE is doing.
Could be a path thing. If you put proper error handling in, you could see how that would go.
Quote:Original post by Sneftel
Quote:Original post by Cromulent
Sorry for the late reply. I've got it working when compiling on the command line but unfortunately it does not work from within Xcode. I guess I'll have to have another look at it to see what the IDE is doing.
Could be a path thing. If you put proper error handling in, you could see how that would go.


Okay you were right, all working correctly now. I should have checked that first I guess.

This topic is closed to new replies.

Advertisement