[C++-sig] Can I import a module in C++ and use in python script ?

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Mon Oct 20 17:37:07 CEST 2003


Le lun 20/10/2003 à 17:16, Atul Kshirsagar a écrit :
> I have following code in my C++ application using
> python extension module "FlPythonModulesud".
> 
> Py_Initialize();
> PyObject *m, *d, *m2;
> m = PyImport_AddModule ("__main__");
> d = PyModule_GetDict (m);
> m2 = PyImport_ImportModuleEx ("FlPythonModulesud", d,
> d, NULL);
> PyDict_SetItemString (d, "FlPythonModulesud", m2);
> 
> 
> I use python in multithreaded environment. I have
> embedded a few C++ classes within pthon using Swig. I
> run python expressions using PyRun_String().
> 
> A sample python expression looks like this;
> 
> from FlPythonModulesud import *
> 
> # Get collection pointer
> collection = FlDataCollectionPtr(Collection)
> # get collection size (num records in collection)
> numRecords = collection.size()
> print numRecords
> 
> Here FlDataCollectionPtr is a embedded class pointer
> and Collection is a variable passed to python.
> 
> What I am trying to do is get rid OFF statement 
> from FlPythonModulesud import * 
> in the script programatically.
> 
> But the above PyImport_ImportModuleEx() doesn't serve
> my purpose.
> 
> Any help will be appreciated !!!
> Atul

You have to call the module init function once python is started. In
your case it should be :

initFlPythonModulesud()

Then you can call the "from FlPythonModulesud import *" using
PyRun_String ! (At least that's what I do and it workd well)

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68 





More information about the Cplusplus-sig mailing list