This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| Python With C++ Submitted by

Hi ,this is a little example that shows how to use python with c++.
Example usage:

       PyVM vm;
       print  mod("foo");
       vm.Init(argv[0]);
       vm.RegiterMod(mod);
       std::string cmd =  "                                   \n"
                          "import foo;                        \n"
                          "foo.mega_print(\"py@exe  HI HII!! \");      ";

        vm.ExecString(cmd.c_str());
        vm.ExecFile("file.py");

Javier Santana ^ ethernet

Currently browsing [py.zip] (32,340 bytes) - [py.cpp] - (2,070 bytes)

    // py.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"

    /////////////////////
    //
    // - PyModule
    //
    /////////////////////

    PyModule::~PyModule()
    {

    		std::vector <PyMethodDef>::iterator i =  methods.begin();
    		for(;i!=methods.end();++i){
    				if((*i).ml_name) delete [] (*i).ml_name;

    		}

    }
    void PyModule::RegisterMethod(const char *name, PyCallback fn)
    {
    			// :((
    			int len = strlen(name);
    			char *p = new char[strlen(name)+1];
    			strcpy(p,name);
    			p[len]=0;
    			PyMethodDef def =
    					{
    						p,	          //name
    						fn,           //callback
    						METH_VARARGS, //callback method
    						NULL		  // ;**
    					};
    			methods.push_back(def);
    }

    /////////////////////
    //
    // - PyVM
    //
    /////////////////////

    bool PyVM::Init(const char *n)
    {
    			End();
    			Py_SetProgramName(const_cast<char*>(n));
    			Py_Initialize();
    			if(Py_IsInitialized())
    				m_init = true;
    			else
    				m_init = false;
    			return ok();
    }

    bool PyVM::ExecString(const char *s)
    {
    		assert(ok());
    		if( -1 == PyRun_SimpleString(const_cast<char*> (s) ))
    			return false;
    		return true;
    }

    //crash with pyrun_simplefile()! :_(
    //http://www.webdocs.org/docs/python/official/faq/008.html#8.7
    bool PyVM::ExecFile(char *n)
    {
    			assert(ok());
    			FILE *f = fopen(n,"r");
    			if(!f) return false;
    			fseek(f,0,SEEK_END);
    			int len =  ftell(f);
    			char *p= new char[len+1];
    			if(!p){
    				fclose(f);
    				return false;
    			}
    			rewind(f);
    			fread(p,len,1,f);
    			p[len]=0;

    			int ret =  ExecString(p);
    			fclose(f);

    			delete [] p;
    			if(-1 == ret)
    					return false;

    			return true;
    }
    bool PyVM::RegiterMod(PyModule &mod)
    {
    			assert(ok());
    			std::list<PyModule*>::iterator i = ModList.begin();
    			for(;i!=ModList.end();++i){
    				if( (*i)->Name() == mod.Name()){
    					return false;
    				}
    			}
    			ModList.push_back(&mod);
    			Py_InitModule(const_cast<char*>(mod.Name().c_str()),mod.Methods());
    			return true;

    }

Currently browsing [py.zip] (32,340 bytes) - [py.h] - (1,156 bytes)

    #ifndef _PY_H_
    #define _PY_H_

    #define BEGIN_REG() 	methods.clear()
    #define REGISTER(x,y) 	RegisterMethod(x,y)
    #define END_REG() \
    		do	{ \
    			PyMethodDef __tmp = {NULL, NULL, 0, NULL};\
    			methods.push_back(__tmp);\
    		}while(0)

    class PyModule
    {
    	public:

    		typedef PyObject *(*PyCallback )(PyObject *, PyObject *);

    		PyModule							(const char *n): m_Name(n) {	  }
    		virtual			    ~PyModule		();
    		PyMethodDef*		 Methods		() {	return &(methods[0]);	}
    		const std::string&   Name			() const    {	return m_Name; 			}
    		void			     RegisterMethod	(const char *, PyCallback );

    	protected:

    		std::vector <PyMethodDef> methods;
    		std::string				  m_Name;

    };

    class PyVM
    {
    	public:

    						PyVM		(): m_init(false) {	}
    		virtual		   ~PyVM		() { 	End();		}
    		void			End			() {	if(ok()){ Py_Finalize(); m_init = false;}	}
    		inline bool		ok			() const { return m_init;	}

    		bool			Init		(const char *);
    		bool			ExecString	(const char *);
    		bool			ExecFile	(char *);
    		bool			RegiterMod	(PyModule &);

    	private:

    		bool				 m_init;
    		std::list<PyModule*> ModList;

    };

    #endif // ~ _PY_H_

Currently browsing [py.zip] (32,340 bytes) - [PyMod.h] - (490 bytes)

    #ifndef _PYMOD_H_
    #define _PYMOD_H_

    //example mod
    class print : public PyModule
    {
    	public:
    	print(const char *n):PyModule(n)
    	{
    		BEGIN_REG();
    			REGISTER("mega_print",print::printer);
    		END_REG();

    	}
    	//method's
    	static PyObject *printer(PyObject *self, PyObject *args)
    	{
    		char *cmd;
    		int sts;
    		if (!PyArg_ParseTuple(args, "s", &cmd))
    			return NULL;
    		sts = puts(cmd);
    		return Py_BuildValue("i", sts);
    	}
    	private:

    };
    #endif // ~_PYMOD_H_

Currently browsing [py.zip] (32,340 bytes) - [StdAfx.cpp] - (289 bytes)

    // stdafx.cpp : source file that includes just the standard includes
    //	py.pch will be the pre-compiled header
    //	stdafx.obj will contain the pre-compiled type information

    #include "stdafx.h"

    // TODO: reference any additional headers you need in STDAFX.H
    // and not in this file

Currently browsing [py.zip] (32,340 bytes) - [StdAfx.h] - (832 bytes)

    // stdafx.h : include file for standard system include files,
    //  or project specific include files that are used frequently, but
    //      are changed infrequently
    //

    #if !defined(AFX_STDAFX_H__A8196DB2_BF67_4B88_BA0D_BAF1905FD4BA__INCLUDED_)
    #define AFX_STDAFX_H__A8196DB2_BF67_4B88_BA0D_BAF1905FD4BA__INCLUDED_

    #if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000

    #include <python/python.h>
    #include <stdio.h>
    #include <assert.h>
    #include <string>
    #include <vector>
    #include <list>
    #include "py.h"
    #include "PyMod.h"

    // TODO: reference additional headers your program requires here

    //{{AFX_INSERT_LOCATION}}
    // Microsoft Visual C++ will insert additional declarations immediately before the previous line.

    #endif // !defined(AFX_STDAFX_H__A8196DB2_BF67_4B88_BA0D_BAF1905FD4BA__INCLUDED_)

Currently browsing [py.zip] (32,340 bytes) - [main.cpp] - (578 bytes)

    //
    // main.cpp
    // ethernet - qualopec@lycos.es
    //
    // to compile and execute you need python22.lib, python22.dll and python headers
    // www.python.org - http://www.python.org/ftp/python/2.2.2/Python-2.2.2.exe
    //

    #include "stdafx.h"

    int main(int argc, char* argv[])
    {

       PyVM vm;
       print  mod("foo");
       vm.Init(argv[0]);
       vm.RegiterMod(mod);
       std::string cmd =  "								    \n"
    					  "import foo;					    \n"
    					  "foo.mega_print(\"py@exe -> HI HII!! \");      ";

    	vm.ExecString(cmd.c_str());
    	vm.ExecFile("file.py");
    	return 0;

    }

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.