Loading modules from files through C++

Roland Plüss roland at rptd.ch
Tue May 20 13:17:37 EDT 2014


On 05/19/2014 03:40 AM, Chris Angelico wrote:
> On Mon, May 19, 2014 at 5:41 AM, Roland Plüss <roland at rptd.ch> wrote:
>> This exec source_code in module.__dict__ , should this not also be doable
>> with PyEval_EvalCode?
> General principle: The more code you write in Python and the less in
> C/C++, the happier and more productive you will be.
>
> Drop into Python as soon as you can, and do all the work from there.
> You won't have to worry about RAM (de)allocation, Unicode (especially
> if you use Python 3 rather than 2), integer overflow, etc, etc, etc.
> Only write lower-level code for the bits that actually demand it; and
> as Stefan has pointed out, Cython is a great help there.
>
> (Which reminds me. I still need some "excuse project" to justify my
> learning Cython. It's good-looking tech but everything I can imagine
> writing seems to already exist.)
>
> ChrisA
Figured out the solution to the problem. Inspected some python imported
files to check out the module is actually constructed. Turns out
something has been missing. In general I needed this to get it working:

PyObject * const loadedModule = Py_InitModule3( fullname, NULL, "Loaded
module" );
PyObject * const moduleDict = PyModule_GetDict( loadedModule ); //
borrowed reference
PyDict_SetItemString( moduleDict, "__builtins__", PyEval_GetBuiltins() );
PyRun_StringFlags( fileContent, Py_file_input, moduleDict, moduleDict,
NULL );

The important part are the last two lines. An important module is
lacking the __builtins__ dictionary member so I had to add it.
Furthermore I had to call the string runner with moduleDict both as
global and local dictionary. With that change the virtual script is
properly loaded and working as it should.

Hopefully this works also in Py3 should I switch some time later. But I
guess it should seeing how simple the import now became.

-- 
Yours sincerely
Plüss Roland

Leader and Head Programmer
- Game: Epsylon ( http://www.indiedb.com/games/epsylon )
- Game Engine: Drag[en]gine ( http://www.indiedb.com/engines/dragengine
, http://dragengine.rptd.ch/wiki )
- Normal Map Generator: DENormGen ( http://epsylon.rptd.ch/denormgen.php )
- As well as various Blender export scripts und game tools

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 263 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20140520/9e6b6e6f/attachment.sig>


More information about the Python-list mailing list