Example #1
1
/*
 * Initial load of the Python module.
 *
 * Based on the parsed plugin options we set some prerequisits like the
 * module path and the module to load. We also load the dictionary used
 * for looking up the Python methods.
 */
static bRC PyLoadModule(bpContext *ctx, void *value)
{
   bRC retval = bRC_Error;
   struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;
   PyObject *sysPath,
            *mPath,
            *pName,
            *pFunc,
            *module;

   /*
    * Extend the Python search path with the given module_path.
    */
   if (p_ctx->module_path) {
      sysPath = PySys_GetObject((char *)"path");
      mPath = PyString_FromString(p_ctx->module_path);
      PyList_Append(sysPath, mPath);
      Py_DECREF(mPath);
   }

   /*
    * Make our callback methods available for Python.
    */
   module = Py_InitModule("bareossd", BareosSDMethods);

   /*
    * Try to load the Python module by name.
    */
   if (p_ctx->module_name) {
      Dmsg(ctx, dbglvl, "Trying to load module with name %s\n", p_ctx->module_name);
      pName = PyString_FromString(p_ctx->module_name);
      p_ctx->pModule = PyImport_Import(pName);
      Py_DECREF(pName);

      if (!p_ctx->pModule) {
         Dmsg(ctx, dbglvl, "Failed to load module with name %s\n", p_ctx->module_name);
         goto bail_out;
      }

      Dmsg(ctx, dbglvl, "Successfully loaded module with name %s\n", p_ctx->module_name);

      /*
       * Get the Python dictionary for lookups in the Python namespace.
       */
      p_ctx->pDict = PyModule_GetDict(p_ctx->pModule); /* Borrowed reference */

      /*
       * Encode the bpContext so a Python method can pass it in on calling back.
       */
      p_ctx->bpContext = PyCreatebpContext(ctx);

      /*
       * Lookup the load_bareos_plugin() function in the python module.
       */
      pFunc = PyDict_GetItemString(p_ctx->pDict, "load_bareos_plugin"); /* Borrowed reference */
      if (pFunc && PyCallable_Check(pFunc)) {
         PyObject *pPluginDefinition,
                  *pRetVal;

         pPluginDefinition = PyString_FromString((char *)value);
         if (!pPluginDefinition) {
            goto bail_out;
         }

         pRetVal = PyObject_CallFunctionObjArgs(pFunc, p_ctx->bpContext, pPluginDefinition, NULL);
         Py_DECREF(pPluginDefinition);

         if (!pRetVal) {
            goto bail_out;
         } else {
            retval = conv_python_retval(pRetVal);
            Py_DECREF(pRetVal);
         }
      } else {
         Dmsg(ctx, dbglvl, "Failed to find function named load_bareos_plugins()\n");
         goto bail_out;
      }
   }

   /*
    * Keep track we successfully loaded.
    */
   p_ctx->python_loaded = true;

   return retval;

bail_out:
   if (PyErr_Occurred()) {
      PyErrorHandler(ctx, M_FATAL);
   }

   return retval;
}
Example #2
0
void ThreadProc( void *data )
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyThreadState *mainThreadState, *myThreadState, *tempState;
    PyInterpreterState *mainInterpreterState;
    
    CMD_LINE_STRUCT* arg = (CMD_LINE_STRUCT*)data;

    // Initialize python inerpreter
    Py_Initialize();
        
    // Initialize thread support
    PyEval_InitThreads();

    // Save a pointer to the main PyThreadState object
    mainThreadState = PyThreadState_Get();

    // Get a reference to the PyInterpreterState
    mainInterpreterState = mainThreadState->interp;

    // Create a thread state object for this thread
    myThreadState = PyThreadState_New(mainInterpreterState);

	// Release global lock
	PyEval_ReleaseLock();
    
	// Acquire global lock
	PyEval_AcquireLock();

    // Swap in my thread state
    tempState = PyThreadState_Swap(myThreadState);

    // Now execute some python code (call python functions)
    pName = PyString_FromString(arg->argv[1]);
    pModule = PyImport_Import(pName);

    // pDict and pFunc are borrowed references 
    pDict = PyModule_GetDict(pModule);
    pFunc = PyDict_GetItemString(pDict, arg->argv[2]);

    if (PyCallable_Check(pFunc)) 
    {
        PyObject_CallObject(pFunc, NULL);
    }
    else {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Swap out the current thread
    PyThreadState_Swap(tempState);

	// Release global lock
	PyEval_ReleaseLock();

    // Clean up thread state
    PyThreadState_Clear(myThreadState);
    PyThreadState_Delete(myThreadState);

    Py_Finalize();
    printf("My thread is finishing...\n");

    // Exiting the thread
#ifdef WIN32
    // Windows code
    _endthread();
#else
    // POSIX code
    pthread_exit(NULL);
#endif
}
Example #3
0
bool EntityApp<E>::installPyModules()
{
	Entities<E>::installScript(NULL);
	//Entity::installScript(g_script.getModule());

	pEntities_ = new Entities<E>();
	registerPyObjectToScript("entities", pEntities_);

	// 安装入口模块
	PyObject *entryScriptFileName = NULL;
	if(componentType() == BASEAPP_TYPE)
	{
		ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getBaseApp();
		entryScriptFileName = PyUnicode_FromString(info.entryScriptFile);
	}
	else if(componentType() == CELLAPP_TYPE)
	{
		ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getCellApp();
		entryScriptFileName = PyUnicode_FromString(info.entryScriptFile);
	}

	if(entryScriptFileName != NULL)
	{
		entryScript_ = PyImport_Import(entryScriptFileName);
		SCRIPT_ERROR_CHECK();
		S_RELEASE(entryScriptFileName);

		if(entryScript_.get() == NULL)
		{
			return false;
		}
	}

	// 添加pywatcher支持
	if(!initializePyWatcher(&this->getScript()))
		return false;

	// 添加globalData, globalBases支持
	pGlobalData_ = new GlobalDataClient(DBMGR_TYPE, GlobalDataServer::GLOBAL_DATA);
	registerPyObjectToScript("globalData", pGlobalData_);

	// 注册创建entity的方法到py
	// 向脚本注册app发布状态
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(),	publish,			__py_getAppPublish,		METH_VARARGS,	0);

	// 注册设置脚本输出类型
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(),	scriptLogType,		__py_setScriptLogType,	METH_VARARGS,	0);
	
	// 获得资源全路径
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(),	getResFullPath,		__py_getResFullPath,	METH_VARARGS,	0);

	// 文件操作
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(),	open,				__py_kbeOpen,			METH_VARARGS,	0);

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_NORMAL", log4cxx::ScriptLevel::SCRIPT_INT))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_NORMAL.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_INFO", log4cxx::ScriptLevel::SCRIPT_INFO))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_INFO.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_ERR", log4cxx::ScriptLevel::SCRIPT_ERR))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_ERR.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_DBG", log4cxx::ScriptLevel::SCRIPT_DBG))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_DBG.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_WAR", log4cxx::ScriptLevel::SCRIPT_WAR))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_WAR.\n");
	}


	if(PyModule_AddIntConstant(this->getScript().getModule(), "NEXT_ONLY", KBE_NEXT_ONLY))
	{
		ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.NEXT_ONLY.\n");
	}
	
	onInstallPyModules();
	return true;
}
Example #4
0
int guava_request_on_message_complete(http_parser *parser) {
  guava_conn_t *conn = (guava_conn_t *)parser->data;
  Request *request = (Request *)conn->request;
  guava_server_t *server = conn->server;

  Router *router = NULL;
  Handler *handler = NULL;

  guava_response_t *resp = guava_response_new();
  guava_response_set_conn(resp, conn);

  Py_ssize_t nrouters = PyList_Size(server->routers);

  do {
    router = (Router *)guava_router_get_best_matched_router((PyObject *)server->routers, (PyObject *)request);
    if (router) {
      if (router->router->type == GUAVA_ROUTER_STATIC) {
        guava_handler_static(router->router, conn, ((Request *)conn->request)->req, resp, on_write, on_sendfile);
        break;
      } else {
        handler = (Handler *)PyObject_CallMethod((PyObject *)router, "route", "(O)", request);
        handler->handler->router = router->router;
      }
    }

    for (Py_ssize_t i = 0; i < nrouters; ++i) {
      router = (Router *)PyList_GetItem(server->routers, i);
      if (router->router->type != GUAVA_ROUTER_CUSTOM) {
        /*
         * Cause we already try to get the best matched router
         * But we still need to pass the custome router in case use defined some speciall routes
         */
        continue;
      }
      Handler *h = (Handler *)PyObject_CallMethod((PyObject *)router, "route", "(O)", request);
      if ((PyObject *)h != Py_None) {
        handler = h;
        handler->handler->router = router->router;
        break;
      }
    }

    if (!guava_handler_is_valid(handler->handler) || handler->handler->flags & GUAVA_HANDLER_404) {
      guava_response_404(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->flags & GUAVA_HANDLER_REDIRECT) {
      PyObject *location = PyTuple_GetItem(handler->handler->args, 0);
      guava_response_302(resp, PyString_AsString(location));
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->router->type == GUAVA_ROUTER_STATIC) {
      guava_handler_static(handler->handler->router, conn, ((Request *)conn->request)->req, resp, on_write, on_sendfile);
      break;
    }

    PyObject *module_name = NULL;
    if (guava_string_equal_raw(handler->handler->package, ".")) {
      module_name = PyString_FromString(handler->handler->module);
    } else {
      module_name = PyString_FromFormat("%s.%s", handler->handler->package, handler->handler->module);
    }

    PyObject *module = PyImport_Import(module_name);
    Py_DECREF(module_name);

    if (!module) {
      fprintf(stderr, "no module named: %s\n", PyString_AsString(module_name));
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    PyObject *cls_name = PyString_FromString(handler->handler->cls);
    PyObject *cls = PyObject_GetAttr(module, cls_name);

    Py_DECREF(module);
    Py_DECREF(cls_name);

    if (!cls) {
      fprintf(stderr, "no cls named: %s\n", PyString_AsString(cls_name));
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    Controller *c = (Controller *)PyObject_CallObject(cls, NULL);

    if (!PyObject_TypeCheck(c, &ControllerType)) {
      fprintf(stderr, "You controller class must inherit from guava.controller.Controller\n");
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    Py_DECREF(cls);
    c->resp = resp;
    c->req = ((Request *)conn->request)->req;
    c->router = handler->handler->router;

    PyObject *r = NULL;
    if (handler->handler->args) {
      r = PyObject_CallMethod((PyObject *)c, handler->handler->action, "O", handler->handler->args);
    } else {
      r = PyObject_CallMethod((PyObject *)c, handler->handler->action, NULL);
    }

    if (!r) {
      Py_DECREF(c);
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      fprintf(stderr, "failed to execute action: %s\n", handler->handler->action);
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->router->session_store && c->SESSION) {
      guava_request_t *r = ((Request *)conn->request)->req;
      PyObject *sid_cookie = PyDict_GetItemString(r->COOKIES, handler->handler->router->session_store->name);
      guava_session_id_t sid = NULL;

      if (sid) {
        sid = guava_string_new(((Cookie *)sid_cookie)->data.value);
      } else {
        sid = guava_session_new_id();
      }

      guava_session_set(handler->handler->router->session_store, sid, c->SESSION);
    }

    Py_DECREF(c);

    guava_response_send(resp, on_write);
  } while(0);

  Py_XDECREF(handler);
  Py_XDECREF(conn->request);

  return 0;
}
Example #5
0
int main(int argc, char *argv[])
{
    Py_Initialize();  
    if(!Py_IsInitialized())   
    {  
        return -1;  
    }  
    
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject* pName;
    PyObject* pModule;
    PyObject* pDict;
    PyObject* pFunc;
    
    pName = PyString_FromString("call");
    pModule = PyImport_Import(pName);
    if(!pModule)
    {
        printf("can't find call.py");
        getchar();
        return -1;
    }
    
    pDict = PyModule_GetDict(pModule);
    if(!pDict)
    {
        return -1;
    }
    
    {
        pFunc = PyDict_GetItemString(pDict,"test");
        if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf("can't find function [test]");
            getchar();
            return -1;
        }
        
        PyObject_CallObject(pFunc,0);
    }
    
    {
        pFunc = PyDict_GetItemString(pDict,"add");
        if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf("can't find function [test]");
            getchar();
            return -1;
        }
        
        PyObject* args = PyTuple_New(2);
        PyTuple_SetItem(args,0,Py_BuildValue("l",3));
        PyTuple_SetItem(args,1,Py_BuildValue("l",4));
        PyObject *pAdded = PyObject_CallObject(pFunc,args);
        int ret = PyInt_AsLong(pAdded);  
        printf("add value:%d\n",ret);
        Py_DECREF(args);
    }    
    
    Py_DECREF(pName);
    Py_DECREF(pDict);
    Py_DECREF(pModule);
    Py_Finalize();    
    system("PAUSE");
    return 0;
}
Example #6
0
static int proxenet_python_initialize_function(plugin_t* plugin, req_t type)
{
	char*	module_name;
	PyObject *pModStr, *pMod, *pFunc;
	const char* function_name;
	bool is_request = (type==REQUEST) ? true : false;


	/* checks */
	if (!plugin->name) {
		xlog_python(LOG_ERROR, "%s\n", "null plugin name");
		return -1;
	}

	if (plugin->pre_function && type == REQUEST) {
                if(cfg->verbose)
                        xlog_python(LOG_WARNING, "Pre-hook function already defined for '%s'\n", plugin->name);
		return 0;
	}

	if (plugin->post_function && type == RESPONSE) {
                if(cfg->verbose)
                        xlog_python(LOG_WARNING, "Post-hook function already defined for '%s'\n", plugin->name);
		return 0;
	}

	function_name = is_request ? CFG_REQUEST_PLUGIN_FUNCTION : CFG_RESPONSE_PLUGIN_FUNCTION;

        module_name = plugin->name;
	pModStr = PYTHON_FROMSTRING(module_name);
	if (!pModStr) {
		PyErr_Print();
		return -1;
	}

	pMod = PyImport_Import(pModStr);
	if(!pMod) {
		xlog_python(LOG_ERROR, "Failed to import '%s'\n", module_name);
		PyErr_Print();
		Py_DECREF(pModStr);
		return -1;
	}

	Py_DECREF(pModStr);

#ifdef DEBUG
	xlog_python(LOG_DEBUG, "Importing '%s.%s'\n", module_name, function_name);
#endif

	/* find reference to function in module */
	pFunc = PyObject_GetAttrString(pMod, function_name);
	if (!pFunc) {
		PyErr_Print();
		return -1;
	}

	if (!PyCallable_Check(pFunc)) {
		xlog_python(LOG_ERROR, "Object in %s is not callable\n", module_name);
		return -1;
	}

	if (is_request)
		plugin->pre_function = pFunc;
	else
		plugin->post_function = pFunc;

	return 0;
}
Example #7
0
	int spyceRequest(webs_t wp, char_t *lpath)
	{
		// initialize python first
		if(!spyInitialized)
		{
			g_pythonParser.Initialize();

			PyEval_AcquireLock();
			PyInterpreterState * mainInterpreterState = g_pythonParser.getMainThreadState()->interp;
			spyThreadState = PyThreadState_New(mainInterpreterState);
			PyThreadState_Swap(spyThreadState);

			PyObject* pName = PyString_FromString("spyceXbmc");
			PyObject* pModule = PyImport_Import(pName);
			Py_XDECREF(pName);

			if(!pModule) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
			else
			{
				PyObject* pDict = PyModule_GetDict(pModule);
				Py_XDECREF(pModule);
				spyFunc = PyDict_GetItemString(pDict, "ParseFile");
				if(!spyFunc) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
				
				else spyInitialized = true;
			}

			PyThreadState_Swap(NULL);
			PyEval_ReleaseLock();
			if(!spyInitialized)
			{
				PyThreadState_Clear(spyThreadState);
				PyThreadState_Delete(spyThreadState);
				g_pythonParser.Finalize();
				return -1;		
			}
			
		}

		PyEval_AcquireLock();
		PyThreadState_Swap(spyThreadState);

		std::string strRequestMethod;
		std::string strQuery = wp->query;
		std::string strCookie;
		int iContentLength = 0;
		
		if (strlen(wp->query) > 0)
		{
			if(wp->flags & WEBS_POST_REQUEST)	strRequestMethod = "POST";
			else if (wp->flags & WEBS_HEAD_REQUEST) strRequestMethod = "HEAD";
			else strRequestMethod = "GET";
		}

		if (wp->flags & WEBS_COOKIE) strCookie = wp->cookie;
		iContentLength = strQuery.length();

		// create enviroment and parse file
		PyObject* pEnv = PyDict_New();
		PyObject* pREQUEST_METHOD = PyString_FromString(strRequestMethod.c_str());
		PyObject* pCONTENT_LENGTH = PyInt_FromLong(iContentLength);
		PyObject* pQUERY_STRING = PyString_FromString(strQuery.c_str());
		PyObject* pHTTP_COOKIE = PyString_FromString(strCookie.c_str());
		PyObject* pCONTENT_TYPE = PyString_FromString(wp->type);
		PyObject* pHTTP_HOST = PyString_FromString(wp->host);
		PyObject* pHTTP_USER_AGENT = PyString_FromString(wp->userAgent ? wp->userAgent : "");
		PyObject* pHTTP_CONNECTION = PyString_FromString((wp->flags & WEBS_KEEP_ALIVE)? "Keep-Alive" : "");

		PyDict_SetItemString(pEnv, "REQUEST_METHOD", pREQUEST_METHOD);
		PyDict_SetItemString(pEnv, "CONTENT_LENGTH", pCONTENT_LENGTH);
		PyDict_SetItemString(pEnv, "QUERY_STRING", pQUERY_STRING);
		PyDict_SetItemString(pEnv, "HTTP_COOKIE", pHTTP_COOKIE);
		//PyDict_SetItemString(pEnv, "CONTENT_TYPE", pCONTENT_TYPE);
		PyDict_SetItemString(pEnv, "HTTP_HOST", pHTTP_HOST);
		PyDict_SetItemString(pEnv, "HTTP_USER_AGENT", pHTTP_USER_AGENT);
		PyDict_SetItemString(pEnv, "HTTP_CONNECTION", pHTTP_CONNECTION);

		PyObject* pResult = PyObject_CallFunction(spyFunc, (char*)"sO", lpath, pEnv);

		Py_XDECREF(pREQUEST_METHOD);
		Py_XDECREF(pCONTENT_LENGTH);
		Py_XDECREF(pQUERY_STRING);
		Py_XDECREF(pHTTP_COOKIE);
		Py_XDECREF(pCONTENT_TYPE);
		Py_XDECREF(pHTTP_HOST);
		Py_XDECREF(pHTTP_USER_AGENT);
		Py_XDECREF(pHTTP_CONNECTION);

		Py_XDECREF(pEnv);

		if(!pResult) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
		else
		{
			char* cResult = PyString_AsString(pResult);
			websWriteBlock(wp, cResult, strlen(cResult));
			Py_XDECREF(pResult);
		}

		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();

	/*
	*	Common exit and cleanup
	*/
		if (websValid(wp)) {
			websPageClose(wp);
		}
		return 0;
	}
Example #8
0
//-------------------------------------------------------------------------------------
bool Bots::installPyModules()
{
	ClientObject::installScript(NULL);
	PyBots::installScript(NULL);

	pPyBots_ = new PyBots();
	registerPyObjectToScript("bots", pPyBots_);
	
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), addBots, __py_addBots,	METH_VARARGS, 0);

	// 注册设置脚本输出类型
	APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(),	scriptLogType,	__py_setScriptLogType,	METH_VARARGS,	0)
	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_NORMAL", log4cxx::ScriptLevel::SCRIPT_INT))
	{
		ERROR_MSG( "Bots::installPyModules: Unable to set KBEngine.LOG_TYPE_NORMAL.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_INFO", log4cxx::ScriptLevel::SCRIPT_INFO))
	{
		ERROR_MSG( "Bots::installPyModules: Unable to set KBEngine.LOG_TYPE_INFO.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_ERR", log4cxx::ScriptLevel::SCRIPT_ERR))
	{
		ERROR_MSG( "Bots::installPyModules: Unable to set KBEngine.LOG_TYPE_ERR.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_DBG", log4cxx::ScriptLevel::SCRIPT_DBG))
	{
		ERROR_MSG( "Bots::installPyModules: Unable to set KBEngine.LOG_TYPE_DBG.\n");
	}

	if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_WAR", log4cxx::ScriptLevel::SCRIPT_WAR))
	{
		ERROR_MSG( "Bots::installPyModules: Unable to set KBEngine.LOG_TYPE_WAR.\n");
	}

	registerScript(client::Entity::getScriptType());

	// 安装入口模块
	PyObject *entryScriptFileName = PyUnicode_FromString(g_kbeSrvConfig.getBots().entryScriptFile);
	if(entryScriptFileName != NULL)
	{
		entryScript_ = PyImport_Import(entryScriptFileName);

		if (PyErr_Occurred())
		{
			INFO_MSG(fmt::format("EntityApp::installPyModules: importing scripts/bots/{}.py...\n",
				g_kbeSrvConfig.getBots().entryScriptFile));

			PyErr_PrintEx(0);
		}

		S_RELEASE(entryScriptFileName);

		if(entryScript_.get() == NULL)
		{
			return false;
		}
	}

	onInstallPyModules();

	return true;
}
Example #9
0
int c_function(int *n, float **mat)
{
  PyObject *pModule  = NULL;
  PyObject *pFunc = NULL;
  PyObject *pArg = NULL;
  PyObject *pRet = NULL;
  PyObject *pName = NULL;

  size_t size = *n;
  npy_intp *dim;
  int i, j;

  dim = (npy_intp *) malloc(sizeof(npy_intp)*(size));

  for (i=0; i < size; i++) dim[i] = size;

  Py_Initialize();

  if (!Py_IsInitialized())
  {
    fprintf(stderr, "nao foi possivel inicializar o python!\n");
    return -1;
  }

  init_numpy(); 

  PyObject* pMat = PyArray_NewFromDescr(
     &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 
     2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL);

  Py_INCREF(pMat);

  pName = PyString_FromString("function");
  pModule = PyImport_Import(pName);

  pFunc = PyObject_GetAttrString(pModule, "py_function");

  if(!PyCallable_Check(pFunc))
  {
    printf("func not callable!\n");
    return -1;
  }

  pArg = PyTuple_New (2);
  PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size));
  PyTuple_SetItem(pArg, 1, pMat);

  pRet = PyObject_CallObject(pFunc, pArg);

  printf("py ret: %s\n", PyString_AsString(pRet));

  Py_DECREF (pMat);
  Py_DECREF (pName);
  Py_DECREF (pModule);
  Py_DECREF (pFunc);
  Py_DECREF (pArg);
  Py_DECREF (pRet);

  Py_Finalize();

  return 0;
}
Example #10
0
int
main()
{
	// initial the interpreter
    char xv[100] = "abcdefg";
    PyObject * tstr = PyString_FromString(xv);
	Py_Initialize();
	if (!Py_IsInitialized()) {
		return -1;
	}
	// import the sys module
	PyRun_SimpleString("import sys");
	// add the current path to sys.path
	PyRun_SimpleString("sys.path.append('./')");

	PyObject * pModule = NULL;
	PyObject * pFunc = NULL;
	PyObject * pName = NULL;
	PyObject * pModule1 = NULL;
	PyObject * pFunc1 = NULL;
	PyObject * pDict = NULL;
	PyObject * pArgs = NULL;
    PyObject * pFunc2 = NULL;

	pName = PyString_FromString("pytest");
	pModule1 = PyImport_Import(pName);
	if (!pModule1) {
		printf("can't find pytest.py");
		getchar();
		return -1;
	}
	pDict = PyModule_GetDict(pModule1);
	if (!pDict) {
		return -1;
	}
	pFunc1 = PyDict_GetItemString(pDict, "add");
	if (!pFunc1 || !PyCallable_Check(pFunc1)) {
		printf("can't find function [add]");
		getchar();
		return -1;
	}
    pFunc2 = PyDict_GetItemString(pDict, "echo");
    if (!pFunc2 || !PyCallable_Check(pFunc2)) {
        printf("can't find function [echo]");
        getchar();
        return -1;
    }
    pArgs = PyTuple_New(1);
    printf("array size = %d \n", PyTuple_Size(pArgs));
    PyTuple_SetItem(pArgs, 0, tstr);
    PyObject_CallObject(pFunc2, pArgs);
	// create a Tuple(2)
	pArgs = PyTuple_New(2);
	// create long int and make Tumple points it
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 3));
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 4));
	// call a function with parameters
	PyObject_CallObject(pFunc1, pArgs);
	// reuse the pFunc1 parameter
	pFunc1 = PyDict_GetItemString(pDict, "foo");
	if(!pFunc1 || !PyCallable_Check(pFunc1)) {
		printf("can't find function [foo]");
		getchar();
		return -1;
	}
	pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 2));
	PyObject_CallObject(pFunc1, pArgs);
	// a another way to import a module
	pModule = PyImport_ImportModule("helloworld");
	// find a function in a module
	pFunc = PyObject_GetAttrString(pModule, "hello");
	// call the function
	PyEval_CallObject(pFunc, NULL);

	// free the memory
	Py_DECREF(pName);
	Py_DECREF(pArgs);
	Py_DECREF(pModule1);
	Py_DECREF(pModule);
	// close python, release the resource
	Py_Finalize();

	return 0;
}
Example #11
0
int *CA_LoadCells(char *pattern, int width) {
    PyObject *pModuleName;  // the name of the module 
    PyObject *pModule;      // the module object
    PyObject *pFunc;        // the callable object 
    PyObject *pWidth;       // the width parameter of the CA
    PyObject *pArgs;        // the argument list to the callable
    PyObject *pResult;      // the result of the python invocation

    char *module_name = "capattern";
    int i;

    // initialize the python interpreter
    Py_Initialize();

    // add current directory to sys.path, so that import can succeed
    // alternative approach is to export: PYTHONPATH=. when starting the executable
    // NOTE: this is somehow wrong as it replaces sys.path
    //PySys_SetPath(".");

    // import the module
    pModuleName = PyString_FromString(module_name);
    pModule = PyImport_Import(pModuleName);

    if (pModule == NULL) {
        fprintf(stderr, "error: could not import module: %s\n", module_name);
        if (PyErr_Occurred()) {
            PyErr_Print();
        }
        return NULL;
    }
    
    // get a reference to the callable with the specified name
    pFunc = PyObject_GetAttrString(pModule, pattern);
    if (pFunc == NULL) {
        fprintf(stderr, "error: could not find callable: %s\n", pattern);
        return NULL;
    }

    if (!PyCallable_Check(pFunc)) {
        fprintf(stderr, "error: %s is not callable\n", pattern);
        return NULL;
    }

    // prepare the arguments for the callable
    pWidth = PyInt_FromLong(width);
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, pWidth);

    // invoke the callable with the arguments
    pResult = PyObject_CallObject(pFunc, pArgs);

    // check for errors
    if (PyErr_Occurred()) {
        PyErr_Print();
        return NULL;
    }

    // check whether the result is a sequence
    if (!PySequence_Check(pResult)) {
        fprintf(stderr, "error: result is not a sequence\n");
        return NULL;
    }

    // check length of returned result
    if (PySequence_Size(pResult) != width) {
       fprintf(stderr, "error: returned sequence has incorrect length\n");
    }

    // allocate cells
    int *cells = (int *) malloc(width * sizeof(int));

    // iterate over elements in sequence
    for (i=0; i<width; i++) {
        // check that the element is an integer
        PyObject *pElement;
        pElement = PySequence_GetItem(pResult, i);
        if (!PyInt_Check(pElement)) {
            fprintf(stderr, "error: element with index %d is not an integer\n", i);
            return NULL;
        }

        // check that the element is equal to one or zero
        int value = PyInt_AsLong(pElement);
        if (!((value == 0) || (value == 1))) {
            fprintf(stderr, "error: element with index %d is not 0 or 1\n", i);
            return NULL;
        }

        // get the cell
        *(cells+i) = value;
    }

    Py_Finalize();
    return cells;
}
Example #12
0
bool obs_module_load()
{
    blog(LOG_INFO, "obs_module_load");
    //Need to init python here



    //load the swig  
    


    Py_Initialize();
    PyEval_InitThreads();
 
    

    /*Must set arguments for guis to work*/

    wchar_t* argv[] = { L"", NULL };
    int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
  
    //SWIG_init();


    PySys_SetArgv(argc, argv);
   
    //need to add to directory

    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
    PyRun_SimpleString("sys.stdout = open('/dev/shm/stdOut.txt','w',1)");
    PyRun_SimpleString("sys.stderr = open('/dev/shm/stdErr.txt','w',1)");
    PyRun_SimpleString("print(sys.version)");





   /*Load a file*/
    
    
    PyObject* pName, *pModule, *pFunc,*argList;
    


    pName = PyUnicode_FromString("source");

    char script[] = "/scripts";
    const char *data_path = obs_get_module_data_path(obs_current_module());
    char *scripts_path = bzalloc(strlen(data_path)+strlen(script));
    strcpy(scripts_path,data_path);
    strcat(scripts_path,script);




    //Add the path to env
    add_to_python_path(scripts_path);
    bfree(scripts_path);


    //PyImport_AppendInittab("_libobs", PyInit_libobs);
    /*Import libobs*/

    
    //Py_XDECREF(main_module);


    //Add our custom stuff to libobs


    //import the script

    pModule = PyImport_Import(pName);
    pyHasError();
    //get the function by name
    if(pModule != NULL) {
      
      PyObject *ns = PyModule_GetDict(pModule);
      Py_INCREF(ns);
      PyObject *py_libobs = PyImport_ImportModuleEx("obspython",ns,ns,NULL);
      Py_INCREF(py_libobs);
      extend_swig_libobs(py_libobs);
      PyModule_AddObject(pModule,"obspython",py_libobs);
      
      pFunc = PyObject_GetAttr(pModule, PyUnicode_FromString("register"));
        if(pFunc != NULL) {
	  argList = Py_BuildValue("()");
            PyObject_CallObject(pFunc,argList);
 	     pyHasError();
	    Py_XDECREF(pFunc);
	    Py_XDECREF(argList);
        }
	Py_XDECREF(pModule);
    }
    Py_XDECREF(pName);
    
    



    //Not implemented yet?
    //obs_register_modal_ui(&myui);

    //Register this base class here
    obs_register_source(&python_source_info);
    


    //Release the thread gill
    PyThreadState* pts = PyGILState_GetThisThreadState();
    PyEval_ReleaseThread(pts);




    return true;
}
bool obs_module_load()
{
    blog(LOG_INFO, "obs_module_load");

    if(!is_python_on_path()){
      blog(LOG_WARNING,
	   "%s:l%i \"Warning could not detect python environment variables attempting to load shared library anyway\"",
	   __func__,
	   __LINE__
	   );      
    }

    // Manually force python to be loaded
#if __GNUC__
    if(!os_dlopen_global(PYTHON_SHARED_LIBRARY_NAME)){
#else
      if(!os_dlopen(PYTHON_SHARED_LIBRARY_NAME)){
#endif
	blog(LOG_ERROR,
	    "%s:l%i \"Error Could not load python shared library %s aborting!\"",
	    __func__,
	    __LINE__,
	    PYTHON_SHARED_LIBRARY_NAME
	    );      
	return false;
    }


    Py_Initialize();
    PyEval_InitThreads();
 

    /*Must set arguments for guis to work*/
    wchar_t* argv[] = { L"", NULL };
    int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
  

    PySys_SetArgv(argc, argv);

    /* Setup logs to a safe place can be changed by user in OBSPythonManager.py register function*/
    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
    /* TODO  change to non platform specific */
    PyRun_SimpleString("sys.stdout = open('./stdOut.txt','w',1)");
    PyRun_SimpleString("sys.stderr = open('./stdErr.txt','w',1)");
    PyRun_SimpleString("print(sys.version)");

    
    /*Load manager from file*/    
    PyObject* pName = NULL;
    PyObject* pModule = NULL;
    PyObject* pFunc = NULL;
    PyObject* argList = NULL;

    bool ret = false;

    char script[] = "/scripts";
    char arch[] = PLUGINARCH;
    const char *data_path = obs_get_module_data_path(obs_current_module());
    char *scripts_path = bzalloc(strlen(data_path)+strlen(script));
    
    strcpy(scripts_path,data_path);
    strcat(scripts_path,script);


    //Add the scripts path to env
    add_to_python_path(scripts_path);

    bfree(scripts_path);
    

    scripts_path = bzalloc(strlen(data_path)+strlen(arch));
    strcpy(scripts_path,data_path);
    strcat(scripts_path,arch);

    //Add the plugin obspython arch path to env
    add_to_python_path(scripts_path);


    /* load the obspython library and extend with manually written functions/objects  */
    PyObject *py_libobs = PyImport_ImportModule("obspython");
    ret = pyHasError();
    if (ret){
      blog(LOG_INFO,
	   "%s:l%i \"Error importing '%s/obspython.py' unloading obs-python\"",
	   __func__,
	   __LINE__,
	   scripts_path
	   );
      goto out;
    }

    extend_swig_libobs(py_libobs);


    //Import the manager script
    pName = PyUnicode_FromString("OBSPythonManager");
    pModule = PyImport_Import(pName);

    ret = pyHasError();
    if (ret){
      blog(LOG_INFO,
	     "%s:l%i \"Error loading '%s/OBSPythonManager.py' unloading obs-python\"",
	     __func__,
	     __LINE__,
	     scripts_path
	     );
      goto out;
    }
    
    //get the function by name
    if(pModule != NULL) {
      PyModule_AddObject(pModule,"obspython",py_libobs);
      pFunc = PyObject_GetAttr(pModule, PyUnicode_FromString("obs_module_load"));
        if(pFunc != NULL) {
	  argList = Py_BuildValue("()");
            PyObject_CallObject(pFunc,argList);
	    ret = pyHasError();
	    if (ret){
	      blog(LOG_INFO,
		   "%s:l%i \"Error running 'register' function in '%s/OBSPythonManager.py' unloading obs-python\"",
		   __func__,
		   __LINE__,
		   scripts_path
		   );
	      goto out;
	    }
	}else{
	  ret = pyHasError();
	  blog(LOG_INFO,
	       "%s:l%i \"Could not find register function in '%s/OBSPythonManager.py' unloading obs-python\"",
	       __func__,
	       __LINE__,
	       scripts_path
	       );
	}
	goto out;
    }

 out:
    bfree(scripts_path);    
    Py_XDECREF(pFunc);
    Py_XDECREF(argList);
    Py_XDECREF(pModule);
    Py_XDECREF(pName); 
    //Release the thread GIL
    PyThreadState* pts = PyGILState_GetThisThreadState();
    PyEval_ReleaseThread(pts);
    if(!ret){    
       return true;
    }else{    
        obs_module_unload();
        return false;
    }
}

void obs_module_unload()
{
    //Shutdown python and call shutdown functions
    blog(LOG_INFO, "obs_module_unload");

    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    UNUSED_PARAMETER(gstate);

    if (Py_IsInitialized()) {
        Py_Finalize();
    }

}
Example #14
0
char *pycall(PgSocket *client, char *username, char *query_str, char *py_file,
		char* py_function) {
	PyObject *pName = NULL, *pModule = NULL, *pFunc = NULL;
	PyObject *pArgs = NULL, *pValue = NULL;
	PyObject *ptype, *perror, *ptraceback;
	char *py_pathtmp, *py_filetmp, *py_path, *py_module, *ext;
	char *res = NULL;

        /* setup python search path */
	py_pathtmp = malloc(strlen(py_file) + 1);
	strcpy(py_pathtmp, py_file);
	py_path = malloc(strlen(py_file) + 20) ;
        sprintf(py_path,"PYTHONPATH=%s",dirname(py_pathtmp)) ;
	putenv(py_path) ;

	/* setup python module name, function name */
	py_filetmp = malloc(strlen(py_file) + 1);
	strcpy(py_filetmp, py_file);
	py_module = (char *) basename(py_filetmp);
	ext = strrchr(py_module, '.');
	if (ext)
		ext[0] = '\0';

        /* Initialize the Python interpreter
         * NOTE: This call is a no-op on subsequent calls, as we do not 
         * call PyFinalize(). This 
         * a) avoids the overhead of repeatedly reloading the interpreter
         * b) allows the use of global variables for persisting data in the
         *    routing / rewriting functions between calls.
         */
	Py_Initialize();

	/* Load python module */
	pName = PyString_FromString(py_module);
	pModule = PyImport_Import(pName);
	if (pModule == NULL) {
		slog_error(client, "Python module <%s> did not load", py_module);
		goto finish;
	}

	/* Prepare to call python function */
	pFunc = PyObject_GetAttrString(pModule, py_function);
	if (!pFunc) {
		slog_error(client, "Python Function <%s> not found in module <%s>",
				py_function, py_module);
		goto finish;
	}
	if (!PyCallable_Check(pFunc)) {
		slog_error(client,
				"Python Function <%s> in module <%s> is not callable!",
				py_function, py_module);
		goto finish;
	}

	/* Call function with two arguments - username and query_str */
	pArgs = PyTuple_New(2);
	pValue = PyString_FromString(username);
	PyTuple_SetItem(pArgs, 0, pValue);
	pValue = PyString_FromString(query_str);
	PyTuple_SetItem(pArgs, 1, pValue);
	pValue = PyObject_CallObject(pFunc, pArgs);
	if (pValue == NULL) {
		slog_error(client, "Python Function <%s> failed to return a value",
				py_function);
		goto finish;
	}
	if (PyString_Check(pValue)) {
		res = malloc(strlen(PyString_AsString(pValue)) + 1);
		strcpy(res, PyString_AsString(pValue));
	} else {
		res = NULL;
	}

	finish:
	if (PyErr_Occurred()) {
		PyErr_Fetch(&ptype, &perror, &ptraceback);
		slog_error(client, "Python error: %s", PyString_AsString(perror));
	}
	free(py_pathtmp);
	free(py_filetmp);
	free(py_path);
	Py_XDECREF(pName);
	Py_XDECREF(pModule);
	Py_XDECREF(pFunc);
	Py_XDECREF(pArgs);
	Py_XDECREF(pValue);
	return res;
}
Example #15
0
static int python_connect(vfs_handle_struct *handle, const char *service, const char *user)
{
	PyObject *pRet, *pArgs, *pValue, *pSysPath;
	const char *pysource_const, *pyarg;
	char pysource[PY_MAXPATH];
	struct pyfuncs *pf;
	int i;

	pf = SMB_MALLOC_P(struct pyfuncs);
	if (!pf) {
		errno = ENOMEM;
		return -1;
	}
	handle->data = (void *)pf;
	handle->free_data = free_python_data;

	memset(pf, 0, sizeof(*pf));

	pysource_const = lp_parm_const_string(SNUM(handle->conn), "vfs_python", "module_name", NULL);
	if (!pysource_const || pysource_const[0] == '\0') {
		DEBUG(1, ("vfs_python: module_name not set!\n"));
		errno = E_INTERNAL;
		return -1;
	}

	/* strlen doesn't count the trailing NULL, so even if they're the same
	   length it's no good. */
	if (strlen(pysource_const) >= sizeof(pysource)) {
		DEBUG(1, ("vfs_python: module_name too long!\n"));
		errno = ENOMEM;
		return -1;
	}

	/* Silly, but some implementations of dirname and basename modify their
	   input parameters. */
	strncpy((char *) &pysource, pysource_const, sizeof(pysource));
	pyarg = dirname((char *) &pysource);

	/* If we have a path, add it to Python's search path. */
	if (pyarg) {
		/* Note PySys_GetObject returns a borrowed reference */
		pSysPath = PySys_GetObject("path"); 
		if (!pSysPath) {
			errno = E_INTERNAL;
			return -1;
		}

		pArgs = PyString_FromString(pyarg);
		if (!pArgs) {
			errno = E_INTERNAL;
			return -1;
		}

		i = PyList_Append(pSysPath, pArgs);
		Py_DECREF(pArgs);
		if (i < 0) {
			errno = E_INTERNAL;
			return -1;
		}
	}

	/* Now actually include the module (by its basename). */
	strncpy((char *) &pysource, pysource_const, sizeof(pysource));
	pyarg = basename((char *) &pysource);

	if (!pyarg || pyarg[0] == '\0') {
		DEBUG(1, ("vfs_python: Invalid module_name!\n"));
		errno = E_INTERNAL;
		return -1;
	}

	pArgs = PyString_FromString(pyarg);
	pf->pModule = PyImport_Import(pArgs);
	Py_DECREF(pArgs);

	if (!pf->pModule) {
		DEBUG(1, ("vfs_python: Failed to load module '%s'. Make sure not to include a trailing '.py' or '.pyc' in your module path.\n", pysource_const));
		PyErr_Print();
		errno = E_INTERNAL;
		return -1;
	}

#define VFS_PY_REQUIRED_MODULE_FUNC(_member, _name) \
	pf->pFunc##_member = PyObject_GetAttrString(pf->pModule, _name); \
	if (!pf->pFunc##_member || !PyCallable_Check(pf->pFunc##_member)) { \
		if (pf->pFunc##_member) Py_DECREF(pf->pFunc##_member); \
		DEBUG(1, ("vfs_python: %s function not found or not callable\n", _name)); \
		errno = E_INTERNAL; \
		return -1; \
	}

#define VFS_PY_OPTIONAL_MODULE_FUNC(_member, _name) \
	pf->pFunc##_member = PyObject_GetAttrString(pf->pModule, _name); \
	if (!pf->pFunc##_member) { \
		pf->pFunc##_member = NULL; \
		PyErr_Clear(); \
	} \
	else if (!PyCallable_Check(pf->pFunc##_member)) { \
		Py_DECREF(pf->pFunc##_member); \
		pf->pFunc##_member = NULL; \
	}

	pf->pErrno = PyObject_GetAttrString(pf->pModule, "vfs_errno");
	if (pf->pErrno && !PyInt_Check(pf->pErrno)) {
		Py_DECREF(pf->pErrno);
		DEBUG(1, ("vfs_python: vfs_errno global variable not an int\n"));
		errno = E_INTERNAL;
		return -1;
	}

	VFS_PY_REQUIRED_MODULE_FUNC(Stat, "stat");
	VFS_PY_REQUIRED_MODULE_FUNC(GetDir, "getdir");
	VFS_PY_REQUIRED_MODULE_FUNC(OpenFile, "open");
	VFS_PY_REQUIRED_MODULE_FUNC(Close, "close");
	VFS_PY_REQUIRED_MODULE_FUNC(Read, "read");
	VFS_PY_REQUIRED_MODULE_FUNC(LSeek, "lseek");

	VFS_PY_OPTIONAL_MODULE_FUNC(Unlink, "unlink");
	VFS_PY_OPTIONAL_MODULE_FUNC(Write, "write");
	VFS_PY_OPTIONAL_MODULE_FUNC(MkDir, "mkdir");
	VFS_PY_OPTIONAL_MODULE_FUNC(Unlink, "unlink");
	VFS_PY_OPTIONAL_MODULE_FUNC(Rename, "rename");
	VFS_PY_OPTIONAL_MODULE_FUNC(FStat, "fstat");
	VFS_PY_OPTIONAL_MODULE_FUNC(DiskFree, "diskfree");
	VFS_PY_OPTIONAL_MODULE_FUNC(Connect, "connect");
	VFS_PY_OPTIONAL_MODULE_FUNC(Disconnect, "disconnect");
	VFS_PY_OPTIONAL_MODULE_FUNC(PRead, "pread");
	VFS_PY_OPTIONAL_MODULE_FUNC(PWrite, "pwrite");
	VFS_PY_OPTIONAL_MODULE_FUNC(Chmod, "chmod");
	VFS_PY_OPTIONAL_MODULE_FUNC(FChmod, "fchmod");
	VFS_PY_OPTIONAL_MODULE_FUNC(Chown, "chown");
	VFS_PY_OPTIONAL_MODULE_FUNC(FChown, "fchown");
	VFS_PY_OPTIONAL_MODULE_FUNC(FTruncate, "ftruncate");
	VFS_PY_OPTIONAL_MODULE_FUNC(FAllocate, "fallocate");
	VFS_PY_OPTIONAL_MODULE_FUNC(Symlink, "symlink");
	VFS_PY_OPTIONAL_MODULE_FUNC(Link, "link");
	VFS_PY_OPTIONAL_MODULE_FUNC(ReadLink, "readlink");
	VFS_PY_OPTIONAL_MODULE_FUNC(IsOffline, "isoffline");
	VFS_PY_OPTIONAL_MODULE_FUNC(GetPath, "getpath");

	// Init done, do connect
	if (pf->pFuncConnect) {
		PY_TUPLE_NEW(3);
		PY_ADD_TO_TUPLE(service, PyString_FromString, 0);
		PY_ADD_TO_TUPLE(user, PyString_FromString, 1);

		pyarg = lp_parm_const_string(SNUM(handle->conn), "vfs_python", "connect_arg", NULL);

		if (pyarg) {
			PY_ADD_TO_TUPLE(pyarg, PyString_FromString, 2);
		} else {
			PyTuple_SetItem(pArgs, 2, Py_None);
		}
		PY_CALL_WITH_ARGS(Connect);

		i = PyInt_AS_LONG(pRet);
		Py_DECREF(pRet);
		return i;
	}
	return 0;
}
// 调用simplehttpserver.py脚本
DWORD WINAPI ThreadFunc(PVOID pVoid)
{
	Py_Initialize();

	if (!Py_IsInitialized())
	{
		std::cout << "Py_Initialize() failed" << std::endl;
		CLogMgr::GetGlobalInstance()->setLog("Py_IsInitialized() failed");
		system("pause");
		return 0;
	}

	if (!PyImport_AddModule("Sample"))
	{
		std::cout << "Host API module could not be created." << std::endl;
	}

	PyObject *module = Py_InitModule("Sample", Methods);
	if (!module)
	{
		std::cout << "Host Api functions could not be initialized." << std::endl;
		return 0;
	}


	int v1 = PyRun_SimpleString("import sys");
	//int v2 = PyRun_SimpleString("sys.path.append('./')");

	PyObject *pName = NULL;
	PyObject *pModule = NULL;
	PyObject *pDict = NULL;
	PyObject *pFunc1 = NULL;
	PyObject *pFunc2 = NULL;
	PyObject *pArgs1 = NULL;
	PyObject *pArgs2 = NULL;
	PyObject *pReturn1 = NULL;
	PyObject *pReturn2 = NULL;

	//载入脚本
	pName = PyString_FromString("simplehttpserver");
	pModule = PyImport_Import(pName);

	if (!pModule)
	{
		std::cout << "can not find simplehttpserver.py" << std::endl;
		CLogMgr::GetGlobalInstance()->setLog("can not find simplehttpserver.py");
		system("pause");
		return 0;
	}

	pDict = PyModule_GetDict(pModule);
	if (!pDict)
	{
		std::cout << "PyModule_GetDict failed" << std::endl;
		CLogMgr::GetGlobalInstance()->setLog("PyModule_GetDict failed");
		system("pause");
		return 0;
	}	


	if (pReturn1 != NULL)
	{
		Py_DECREF(pReturn1);
	}

	if (pName != NULL)
	{
		Py_DECREF(pName);
	}

	if (pArgs1 != NULL)
	{
		Py_DECREF(pArgs1);
	}

	if (pArgs2 != NULL)
	{
		Py_DECREF(pArgs2);
	}

	if (pModule != NULL)
	{
		Py_DECREF(pModule);
	}

	if (pFunc1 != NULL)
	{
		Py_DECREF(pFunc1);
	}

	if (pFunc2 != NULL)
	{
		Py_DECREF(pFunc2);
	}

	if (pReturn2 != NULL)
	{
		Py_DECREF(pReturn2);
	}

	//关闭python
	Py_Finalize();

	return 0;
}
Example #17
0
int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.insert(0, '')");

    /* Module name */
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
private int linkgw_create(struct occi_category * optr, void * vptr, struct rest_request * rptr)
{
	struct occi_kind_node * nptr;
	struct linkgw * pptr;
	char sendstr[1024];
	char strtmp[1024];
	char srcdir[1024];
	char * response = NULL;
	char * token;
	FILE * exp_file;
	listcc categoryAtr;
	PyObject    *pName=NULL, *pModule=NULL, *pDict=NULL, *pFunc=NULL,*result=NULL;

	PyThreadState* pythr=NULL;
	if (!( nptr = vptr ))
		return(0);
	else if (!( pptr = nptr->contents ))
		return(0);

	if(!(pptr->name)) strcpy(sendstr," ");
	else if(pptr->name[0]=='\0') strcpy(sendstr," ");
	else strcpy(sendstr,pptr->name);
	if(!(pptr->intercloudGW)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->intercloudGW[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->intercloudGW,',');
	if(!(pptr->account)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->account[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->account,',');
	if(!(pptr->gwsrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->gwsrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->gwsrc,',');
	if(!(pptr->gwdst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->gwdst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->gwdst,',');
	if(!(pptr->tunnelproto)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->tunnelproto[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->tunnelproto,',');
	if(!(pptr->addressgresrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->addressgresrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->addressgresrc,',');
	if(!(pptr->addressgredst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->addressgredst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->addressgredst,',');
	if(!(pptr->prefix)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->prefix[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->prefix,',');
	if(!(pptr->authenticationkey)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->authenticationkey[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->authenticationkey,',');
	if(!(pptr->endpointsrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->endpointsrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->endpointsrc,',');
	if(!(pptr->endpointdst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->endpointdst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->endpointdst,',');
	if(!(pptr->state)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->state[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->state,',');
		//           python interface
		sprintf(srcdir,"%s/pyaccords/pysrc",PYPATH);
		pythr = Py_NewInterpreter();
		python_path(srcdir);
		pName = PyString_FromString("linkgw");
		if(pName == NULL) printf("erro: in linkgw no such file name\n");
		else pModule = PyImport_Import(pName);
		if(pModule == NULL) printf("error: failed to load linkgw module\n");
		else pDict = PyModule_GetDict(pModule);
		if(pDict == NULL) printf("error: failed to load dict name in linkgw module\n");
		else pFunc = PyDict_GetItemString(pDict,"create");
		if(pFunc == NULL) printf("error: failed to load create function in linkgw module\n");
		else result=PyObject_CallFunction(pFunc,"s",sendstr);
		if(result) response=allocate_string(PyString_AsString( result ));
		Py_DECREF(pModule);
		Py_DECREF(pName);
		Py_EndInterpreter(pythr);

	resetListe(&categoryAtr);
	token= strtok(response,",");
	for(; token != NULL ;)
	{
		addBacke(&categoryAtr,token);
		token=strtok(NULL, ",");
	}
	elemm *pelem = categoryAtr.first;
	if(pelem){
		pptr->name = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->intercloudGW = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->account = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->gwsrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->gwdst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->tunnelproto = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->addressgresrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->addressgredst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->prefix = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->authenticationkey = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->endpointsrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->endpointdst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->state = pelem->value;
	}
	return 1;
}
void CMAC_net::plot_contourf() {

    Py_Initialize();
    import_array1();
    PyObject* p_name, *p_module, *p_dict, *p_func, *p_value, *format_expression,
        *run_expression, *run_script, *traceback_module, *python_module,
        *traceback_dictionary, *python_dictionary;
    traceback_module = PyImport_ImportModule("traceback");
    python_module = PyImport_ImportModule("python_fun");

    if (traceback_module && python_module) {
        traceback_dictionary = PyModule_GetDict(traceback_module);
        python_dictionary = PyModule_GetDict(python_module);

        format_expression =
            PyDict_GetItemString(traceback_dictionary, "format_expression");

        run_expression =
            PyDict_GetItemString(python_dictionary, "run_expression");

        run_script = PyDict_GetItemString(python_dictionary, "run_script");

        if (format_expression && run_expression && run_script) {
            if (PyCallable_Check(format_expression) &&
                PyCallable_Check(run_expression) &&
                PyCallable_Check(run_script)) {
            }
        }
    }
    fexcp = PyDict_GetItemString(dict1)

        const int res = 4;
    float** x = new float* [res];
    float** y = new float* [res];
    float** z = new float* [res];

    x[0] = new float[res];
    x[1] = x[0] + res;
    x[2] = x[1] + res;

    y[0] = new float[res];
    y[1] = y[0] + res;
    y[2] = y[1] + res;

    z[0] = new float[res];
    z[1] = z[0] + res;
    z[2] = z[1] + res;

    int mdim[] = {res, res};

    float x_step =
        interval_width[0] * (float)_tile_resolution / ((float)res - 1);
    float y_step =
        interval_width[1] * (float)_tile_resolution / ((float)res - 1);
    float input_vals[2];
    std::ofstream fout;
    fout.open("plot_contourf_tmp.txt");

    for (int i = 0; i < res; i++) {
        for (int j = 0; j < res; j++) {
            x[i][j] = _range_inputs[0][0] + x_step * (float)i;
            y[i][j] = _range_inputs[0][0] + y_step * (float)j;
            input_vals[0] = x[i][j];
            input_vals[1] = y[i][j];
            sim(&z[i][j], input_vals);
            fout << x[i][j] << "," << y[i][j] << "," << z[i][j];

            printf("(%.2f,%.2f,%.2f)", x[i][j], y[i][j], z[i][j]);
            if (j < res - 1) {
                fout << ",";
                std::cout << ",";
            }
        }
        fout << std::endl;
        printf("\n");
    }

    fout.close();

    PyObject* x_mat = PyArray_SimpleNewFromData(2, mdim, PyArray_DOUBLE, x[0]);

    char full_path[256];
    char p_path[256];
    getcwd(full_path, 255);
    strcpy(p_path, "sys.path.append(\"");
    strcat(p_path, full_path);
    strcat(p_path, "\")");

    PyRun_SimpleString("import sys");
    PyRun_SimpleString(p_path);

    p_name = PyString_FromString("py_plot");
    p_module = PyImport_Import(p_name);
    if (p_module == NULL) {
        printf("Failed to open py_plot.py");
    }
    p_dict = PyModule_GetDict(p_module);
    p_func = PyDict_GetItemString(p_dict, "plot_contourf");
    if (PyCallable_Check(p_func)) {
        PyObject_CallObject(p_func, NULL);
    } else {
        PyErr_Print();
    }

    Py_DECREF(p_module);
    Py_DECREF(p_name);
    Py_Finalize();

}
Example #20
0
// -------------------------------------------------------------------------
// This software is furnished "as is", without technical
// support, and with no warranty, express or implied, as to its usefulness for
// any purpose.
//
// gcal.c 
//    This file acts as the wrapper around the sp_func.py python library
//
// Author: Vedvyas Shanbhogue
// ------------------------------------------------------------------------*/

#ifdef IDENT_C
static const char* const <filename>_c_Id = "$Id$";
#endif

#include <Python.h>

// -- global -----------------------------------------------------------------
// get_calendar_events()
//
// Returns:
//     0 - success 
//     1 - error
// On success return, the duration is set to the duration of the event
// if no event was found then duration is returned as 0
// -------------------------------------------------------------------------*/
int 
get_calendar_events(
    time_t *duration)
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
    struct tm start_time, end_time;
    char *start, *end, *name;
    char *argv[] = {
        "sp",
        "sp_func",
        "get_cal_events"
    };

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyString_FromString(argv[1]);

    // Load the module object
    PySys_SetArgv(1, argv);
    PyErr_Print();
    pModule = PyImport_Import(pName);
    PyErr_Print();

    // pDict is a borrowed reference 
    pDict = PyModule_GetDict(pModule);

    // pFunc is also a borrowed reference 
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    if ( !PyCallable_Check(pFunc) ) {
        PyErr_Print();
        Py_DECREF(pModule);
        Py_DECREF(pName);
        Py_Finalize();
        return 1;
    }

    // Get the calendar events from google calendar
    pValue = PyObject_CallObject(pFunc, NULL);

    // Extract the start time, end time and event name strings
    if ( PyArg_ParseTuple(pValue, "sss", &start, &end, &name) == 0 )
    {
        PyErr_Print();
        Py_DECREF(pModule);
        Py_DECREF(pName);
        Py_Finalize();
        return 1;
    }

    *duration = 0;

    // check if any event returned
    if ( strlen(start) && strlen(end) && strlen(name) &&
         (strcmp(name, "Sprinkler On") == 0) ) {

        // Turn time strings into struct tm
        strptime(start, "%Y-%m-%dT%T", &start_time);
        strptime(end, "%Y-%m-%dT%T", &end_time);

        // Check if it is time to start the sprinker
        if ( time(NULL) >= mktime(&start_time) &&
             time(NULL) < mktime(&end_time) ) {
            // Time to start the sprinker for specified duration
            *duration = mktime(&end_time) - time(NULL);
        }
    }

    Py_DECREF(pModule);
    Py_DECREF(pName);
    Py_Finalize();
    return 0;
}
Example #21
0
int main(int argc, char** argv)
{
    // 初始化Python
    //在使用Python系统前,必须使用Py_Initialize对其
    //进行初始化。它会载入Python的内建模块并添加系统路
    //径到模块搜索路径中。这个函数没有返回值,检查系统
    //是否初始化成功需要使用Py_IsInitialized。

    Py_Initialize();

    // 检查初始化是否成功
    if ( !Py_IsInitialized() )
    {
        return -1;
    }

    // 添加当前路径
    //把输入的字符串作为Python代码直接运行,返回0
    //表示成功,-1表示有错。大多时候错误都是因为字符串
    //中有语法错误。
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;

    // 载入名为pytest的脚本
    pName = PyString_FromString("pytest");
    pModule = PyImport_Import(pName);
    if ( !pModule )
    {
        printf("can't find pytest.py");
        getchar();
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict )
    {
        return -1;
    }

    // 找出函数名为add的函数
    pFunc = PyDict_GetItemString(pDict, "add");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [add]");
        getchar();
        return -1;
    }

    // 参数进栈
    *pArgs;
    pArgs = PyTuple_New(2);

    //  PyObject* Py_BuildValue(char *format, ...)
    //  把C++的变量转换成一个Python对象。当需要从
    //  C++传递变量到Python时,就会使用这个函数。此函数
    //  有点类似C的printf,但格式不同。常用的格式有
    //  s 表示字符串,
    //  i 表示整型变量,
    //  f 表示浮点数,
    //  O 表示一个Python对象。

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

    // 调用Python函数
    PyObject_CallObject(pFunc, pArgs);

    //下面这段是查找函数foo 并执行foo
    pFunc = PyDict_GetItemString(pDict, "foo");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [foo]");
        getchar();
        return -1;
    }

    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",2)); //

    PyObject_CallObject(pFunc, pArgs);


    Py_DECREF(pName);
    Py_DECREF(pArgs);
    Py_DECREF(pModule);

    // 关闭Python
    Py_Finalize();
    return 0;
} 
Example #22
0
void pycon_open(){
	//initialise python console
	Py_Initialize();
	PyRun_SimpleString("print 'python present.'");
	Py_InitModule("tpt", EmbMethods);

	//change the path to find all the correct modules
	PyRun_SimpleString("import sys\nsys.path.append('./tptPython.zip')\nsys.path.append('.')");
	//load the console module and whatnot
#ifdef PYEXT
	PyRun_SimpleString(tpt_console_py);
	printf("using external python console file.\n");
	pname=PyString_FromString("tpt_console");//create string object
	pmodule = PyImport_Import(pname);//import module
	Py_DECREF(pname);//throw away string
#else
	tpt_console_obj = PyMarshal_ReadObjectFromString(tpt_console_pyc+8, sizeof(tpt_console_pyc)-8);
	pmodule=PyImport_ExecCodeModule("tpt_console", tpt_console_obj);
#endif
	
	if (pmodule!=NULL)
	{
		pfunc=PyObject_GetAttrString(pmodule,"handle");//get the handler function
		if (pfunc && PyCallable_Check(pfunc))//check if it's really a function
		{
			printf("python console ready to go.\n");
		}
		else
		{
			PyErr_Print();
			printf("unable to find handle function, mangled console.py?\n");
			pyready = 0;
			pygood = 0;
		}

		pstep=PyObject_GetAttrString(pmodule,"step");//get the handler function
		if (pstep && PyCallable_Check(pstep))//check if it's really a function
		{
			printf("step function found.\n");
		}
		else
		{
			printf("unable to find step function. ignoring.\n");
		}

		pkey=PyObject_GetAttrString(pmodule,"keypress");//get the handler function
		if (pstep && PyCallable_Check(pkey))//check if it's really a function
		{
			printf("key function found.\n");
		}
		else
		{
			printf("unable to find key function. ignoring.\n");
		}
	}
	else
	{
		//sys.stderr
		PyErr_Print();
		printf("unable to find console module, missing file or mangled console.py?\n");
		pyready = 0;
		pygood = 0;
	}
}
int importPythonModule (char *binImg1_data,
                        int   binImg1_data_len,
                        char *binImg2_data,
                        char  binImg2_data_len)
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;

    int i;

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault("face");
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL)
    {
        /* pFunc is a new reference */
        pFunc = PyObject_GetAttrString(pModule, "get_images_from_cpp");

        if (pFunc && PyCallable_Check(pFunc))
        {
            pArgs = PyTuple_New(2);

            pValue = PyBytes_FromStringAndSize ( binImg2_data, binImg1_data_len);;

            if (!pValue)
            {
               Py_DECREF(pArgs);
               Py_DECREF(pModule);
               
               fprintf(stderr, "Cannot convert argument\n");
               return 1;
            }

            /* pValue reference stolen here: */
            PyTuple_SetItem(pArgs, 0, pValue);

            pValue = PyBytes_FromStringAndSize ( binImg2_data, binImg2_data_len);;

            if (!pValue)
            {
               Py_DECREF(pArgs);
               Py_DECREF(pModule);
      
               fprintf(stderr, "Cannot convert argument\n");
               return 1;
            }

            /* pValue reference stolen here: */
            PyTuple_SetItem(pArgs, 1, pValue);

            pValue = PyObject_CallObject(pFunc, pArgs);

            Py_DECREF(pArgs);

            if (pValue != NULL)
            {
                printf("Result of call: %f\n", PyLong_AsDouble(pValue));
                Py_DECREF(pValue);
            }

            else
            {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }

        else
        {
            if (PyErr_Occurred())
            {
                PyErr_Print();
            }
            
            fprintf(stderr, "Cannot find function \"%s\"\n", "get_images_from_cpp");
        }
      

        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
 
   }
      
   else
   {
      PyErr_Print();
      fprintf(stderr, "Failed to load \"%s\"\n", "face");
         
      return 1;
   }

   Py_Finalize();

   return 0;
}
Example #24
0
static foreign_t python_run_script(term_t cmd, term_t fun) {
  char si[256], sf[256];
  size_t len = 255, len1 = 255;
  PyObject *pName, *pModule, *pFunc;
  PyObject *pArgs = NULL, *pValue;
  char *s;

  s = si;
  if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION) &&
      (s = sf) != NULL &&
      PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) {

#if PY_MAJOR_VERSION < 3
    pName = PyString_FromString("rbm");
#else
    // asssumes UTF-8
    pName = PyUnicode_FromString("rbm");
#endif
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    PyErr_Clear();
    Py_DECREF(pName);

    if (pModule != NULL) {
      pFunc = PyObject_GetAttrString(pModule, sf);
      /* pFunc is a new reference */

      if (pFunc && PyCallable_Check(pFunc)) {
        pValue = PyObject_CallObject(pFunc, pArgs);
        if (pValue != NULL) {
          Py_DECREF(pValue);
        } else {
          Py_DECREF(pFunc);
          Py_DECREF(pModule);
          PyErr_Print();
          fprintf(stderr, "Call failed\n");
          {
            return false;
          }
        }
      } else {
        if (PyErr_Occurred())
          PyErr_Print();
        fprintf(stderr, "Cannot find function \"%s\"\n", sf);
      }
      Py_XDECREF(pFunc);
      Py_DECREF(pModule);
    } else {
      PyErr_Print();
      {
        return false;
      }
    }
    {
      return true;
    }
  }
  {
    return false;
  }
}
Example #25
0
struct matcher_entry *check_block_params(struct matcher_entry *head)
{

    if(head->name == NULL) {
        printf("You must specify block name\n");
        return NULL;
    }

    if(head->match == NULL) {
        printf("Error: block \"%s\" missing match!\n", head->name);
        return NULL;
    }

#ifdef HAVE_PYTHON
    if((head->response == NULL || head->response_len < 1 || head->response_len > MATCHER_MAX_RESPONSE) && head->pyfunc == NULL) {
#else
    if((head->response == NULL || head->response_len < 1 || head->response_len > MATCHER_MAX_RESPONSE)) {
#endif
        printf("Error: block \"%s\" has missing or malformed response/pymodule!\n", head->name);
        return NULL;
    }

    if(!head->proto) {
        printf("Error: block \"%s\" has missing proto\n", head->name);
        return NULL;
    }

    if(head->dst_port >= 65535) {
        printf("Error: block \"%s\" has incorrect dst port\n", head->name);
        return NULL;
    }
    if(head->src_port >= 65535) {
        printf("Error: block \"%s\" has incorrect src port\n", head->name);
        return NULL;
    }
    return head;
}

struct matcher_entry *parse_matchers_file(char *matcher_file_path)
{

    FILE *matcher_file;
    char matcher_line[MATCHER_MAX_LEN];
    struct matcher_entry *head = NULL;
    int line_no = 0;

    matcher_file = fopen(matcher_file_path, "r");

    if(matcher_file == NULL) {
        perror("fopen");
        return NULL;
    }

    while(fgets(matcher_line, MATCHER_MAX_LEN, matcher_file) != NULL) {
        char command[64] = {0};
        char *argument, *ptr;
        const char *errptr;
        int arglen, lenread=0;
        int c, fd;
#ifdef HAVE_PYTHON
        int pyinitialized=0;
#endif
        struct stat statbuf;

        line_no++;

        matcher_line[MATCHER_MAX_LEN - 1] = 0;

        sscanf(matcher_line, "%64s", command);

        if(command[0] == 0 || command[0] == '#') {
            continue;
        }

        argument = matcher_line + strlen(command);
        // skip over any whitespace
        while(*argument == 0x20 || *argument == 0x09) {
            argument++;
        }

        arglen = strlen(argument);

        // truncate any new-lines etc
        for(ptr = argument + arglen -1; ptr > argument ; ptr--) {
            if(*ptr == '\n' || *ptr == '\r') {
                *ptr = 0;
            }
        }

        // start parsing commands
        if(strcmp(command, "begin") == 0) {
            struct matcher_entry *tmp = malloc(sizeof(struct matcher_entry));
            if(tmp == NULL) {
                perror("malloc");
                return NULL;
            }

            // need to zero this struct
            bzero(tmp, sizeof(struct matcher_entry));

            tmp->next = head;
            head = tmp;

            strncpy(head->name, argument, sizeof(head->name));

        } else {
            if(head == NULL) {
                printf("Error in matchers file line %u\n", line_no);
                return NULL;
            }

            if(strcmp(command, "match") == 0) {
                // the regex to match
                head->match = pcre_compile(argument, PCRE_MULTILINE|PCRE_DOTALL, &errptr, &c, NULL);
                if(head->match == NULL) {
                    printf("Error at character %d in pattern: \"%s\" (%s)\n", c, argument, errptr);
                    return NULL;
                }
            } else if(strcmp(command, "ignore") == 0) {
                // the regex to ignore
                head->ignore = pcre_compile(argument, PCRE_MULTILINE|PCRE_DOTALL, &errptr, &c,NULL);

                if(head->ignore == NULL) {
                    printf("Error at character %d in pattern: \"%s\" (%s)\n", c, argument, errptr);
                    return NULL;
                }
            } else if(strcmp(command, "option") == 0) {
                if(strcmp(argument, "reset") == 0) {
                    head->options |= MATCHER_OPTION_RESET;
                } else {
                    printf("Unknown option: %s\n", argument);
                    return NULL;
                }
            } else if(strcmp(command, "proto") == 0) {
                if(strcmp(argument, "tcp") == 0) {
                    head->proto = MATCHER_PROTO_TCP;
                } else if(strcmp(argument, "udp") == 0) {
                    head->proto = MATCHER_PROTO_UDP;
                } else if(strcmp(argument, "any") == 0) {
                    head->proto = MATCHER_PROTO_ANY;
                } else {
                    printf("Unknown proto: %s\n", argument);
                    return NULL;
                }
            } else if(strcmp(command, "dst_port") == 0) {
                head->dst_port = atoi(argument);
            } else if(strcmp(command, "src_port") == 0) {
                head->src_port = atoi(argument);
            } else if(strcmp(command, "response") == 0) {
                // path to the file to load the response from
                if((fd = open(argument, O_RDONLY)) < 0) {
                    printf("Error opening file: %s\n", argument);
                    perror("open");
                    return NULL;
                }

                if(fstat(fd, &statbuf) < 0) {
                    perror("stat");
                    return NULL;
                }

                if(statbuf.st_size > MATCHER_MAX_RESPONSE) {
                    printf("Error: file %s is too large! (Maximum size is %u)\n", argument, MATCHER_MAX_RESPONSE);
                    return NULL;
                }

                head->response = malloc(statbuf.st_size + 1);
                if(head->response == NULL) {
                    perror("malloc");
                    return NULL;
                }

                while((c = read(fd, head->response + lenread, statbuf.st_size - lenread)) < statbuf.st_size) {
                    lenread += c;
                    printf("read %d bytes\n", lenread);
                }

                lenread += c;

                head->response_len = lenread;

#ifdef HAVE_PYTHON
            } else if(strcmp(command, "pymodule") == 0) {
                if(!pyinitialized) {
                    setenv("PYTHONPATH", PYTHONPATH, 1);
                    Py_Initialize();
                    pyinitialized = 1;
                }
                PyObject *module = PyImport_Import(PyString_FromString(argument));
                if(module == NULL) {
                    PyErr_Print();
                    printf("Error loading module: %s\n", argument);
                    return NULL;
                }

                head->pyfunc = PyObject_GetAttrString(module, PYFUNCNAME);
                if(head->pyfunc == NULL) {
                    PyErr_Print();
                    printf("No function named '"PYFUNCNAME"' in module: %s\n", argument);
                    return NULL;
                }
#endif
            } else if(strcmp(command, "end") == 0) {
                // now's a good time to make sure the block had everything we care about..
                if(head && !(head = check_block_params(head))) {
                    return NULL;
                }
            } else {
                printf("Unknown command at line %u\n", line_no);
                return NULL;
            }
        }
    }
    return head;
}
Example #26
0
void _um_mod_init(char *initargs)
{
	const char *name;
	char *tmphs, *cwd;
	int i;

	PyObject *pName, *pTmpObj, *pTmpFunc, *pTmpDict;

	GMESSAGE("umpyew init");

	if (!strlen(initargs))
	{
		GERROR("You must specify the Python module name.");
		return;
	}

	name = initargs;
	
	s.name="Prototypal Python bindings for *MView";
	s.code=0x07;
	s.syscall=(sysfun *)calloc(scmap_scmapsize,sizeof(sysfun));
	s.socket=(sysfun *)calloc(scmap_sockmapsize,sizeof(sysfun));

	Py_Initialize();
	Py_InitModule("umpyew", pEmbMethods);
	
	pEmptyTuple = PyTuple_New(0);
	pName = PyString_FromString(name);


	cwd = getcwd(NULL, 0);
	if (cwd)
	{
		setenv("PYTHONPATH", cwd, 0);
		free(cwd);
	}

	pModule = PyImport_Import(pName);
	Py_DECREF(pName);

	if (!pModule)
	{
		GERROR("Error loading Python module %s.\nIt has been searched for in the following path:\n%s", name, getenv("PYTHONPATH"));
		PyErr_Print();
		return;
	}

	/*
	 * Add ctl
	 */
	if ((ps.ctl = PyObject_GetAttrString(pModule, "modCtl")) && PyCallable_Check(ps.ctl))
		s.ctl = ctl;
	else
	{
		GDEBUG(2, "function modCheckFun not defined in module %s", name);
		s.ctl = umpyew_alwayszero;
		Py_XDECREF(ps.ctl);
	}

	/*
	 * Add checkfun
	 */
	if ((ps.checkfun = PyObject_GetAttrString(pModule, "modCheckFun")) && PyCallable_Check(ps.checkfun))
		s.checkfun = checkfun;
	else
	{
		GDEBUG("2, function modCheckFun not defined in module %s", name);

		/* This makes the module almost useless, but we respect its author's will. */
		s.checkfun = (epoch_t(*)())umpyew_alwayszero;
		Py_XDECREF(ps.checkfun);
	}
	
	/*
	 * Add ctlhs
	 */
	MCH_ZERO(&(s.ctlhs));
	pTmpObj = PyObject_GetAttrString(pModule, "modCtlHistorySet");

	if (pTmpObj && PyList_Check(pTmpObj))
		for (i = 0; i < PyList_Size(pTmpObj); i++)
			if ((tmphs = PyString_AsString(PyList_GET_ITEM(pTmpObj, i))))
			{
				if (!strcmp(tmphs, "proc"))
					MCH_SET(MC_PROC, &(s.ctlhs));
				else if (!strcmp(tmphs, "module"))
					MCH_SET(MC_MODULE, &(s.ctlhs));
				else if (!strcmp(tmphs, "mount"))
					MCH_SET(MC_MOUNT, &(s.ctlhs));
			}

	Py_XDECREF(pTmpObj);

	/*
	 * Call modInit, if present
	 */
	pTmpObj = PyObject_GetAttrString(pModule, "modInit");
	if (pTmpObj && PyCallable_Check(pTmpObj))
		PyObject_CallObject(pTmpObj, pEmptyTuple);
	Py_XDECREF(pTmpObj);


	/*
	 * Add system calls
	 */
	ps.syscall = calloc(scmap_scmapsize, sizeof(PyObject*));

	PYTHON_SYSCALL(open, sysOpen);
	PYTHON_SYSCALL(close, sysClose);
	PYTHON_SYSCALL(access, sysAccess);
	PYTHON_SYSCALL(mkdir, sysMkdir);
	PYTHON_SYSCALL(rmdir, sysRmdir);
	PYTHON_SYSCALL(chmod, sysChmod);
	PYTHON_SYSCALL(chown, sysChown);
	PYTHON_SYSCALL(lchown, sysLchown);
	PYTHON_SYSCALL(unlink, sysUnlink);
	PYTHON_SYSCALL(link, sysLink);
	PYTHON_SYSCALL(symlink, sysSymlink);
	PYTHON_SYSCALL(stat64, sysStat64);
	PYTHON_SYSCALL(lstat64, sysLstat64);
	PYTHON_SYSCALL(fstat64, sysFstat64);
	PYTHON_SYSCALL(statfs64, sysStatfs64);
	PYTHON_SYSCALL(fstatfs64, sysStatfs64);
	PYTHON_SYSCALL(readlink, sysReadlink);
	PYTHON_SYSCALL(lseek, sysLseek);
	PYTHON_SYSCALL(utime, sysUtime);
	PYTHON_SYSCALL(utimes, sysUtimes)
	PYTHON_SYSCALL(read, sysRead);
	PYTHON_SYSCALL(write, sysWrite);
	PYTHON_SYSCALL(pread64, sysPread64);
	PYTHON_SYSCALL(pwrite64, sysPwrite64);

	add_service(&s);
}
Example #27
0
 virtual void load(const gcore::Path &path, lwc::Registry *reg) {
   
   std::string modulename = path.basename();
   modulename = modulename.substr(0, modulename.length()-3);
   
   gcore::Path dirname = path;
   dirname.pop();
   dirname.makeAbsolute().normalize();
   
   addToSysPath(dirname);
   
   PyObject *pymodname;
   pymodname = PyString_FromString(modulename.c_str());
   PyObject *mod = PyImport_Import(pymodname);
   Py_DECREF(pymodname);
   
   if (!mod) {
     std::cout << "pyloader: Could not load python module" << std::endl;
     PyErr_Print();
     return;
   }
   
   PyObject *getCountFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeCount");
   if (!getCountFunc || !PyCallable_Check(getCountFunc)) {
     if (getCountFunc) {
       Py_DECREF(getCountFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *getNameFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeName");
   if (!getNameFunc || !PyCallable_Check(getNameFunc)) {
     Py_DECREF(getCountFunc);
     if (getNameFunc) {
       Py_DECREF(getNameFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *getClassFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeClass");
   if (!getClassFunc || !PyCallable_Check(getClassFunc)) {
     Py_DECREF(getCountFunc);
     Py_DECREF(getNameFunc);
     if (getClassFunc) {
       Py_DECREF(getClassFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *count = PyObject_CallObject(getCountFunc, NULL);
   long n = PyInt_AsLong(count);
   Py_DECREF(count);
   
   PyObject *args = PyTuple_New(1);
   
   for (long i=0; i<n; ++i) {
     // will this DECREF the old index?
     PyTuple_SetItem(args, 0, PyInt_FromLong(i));
     
     PyObject *pname = PyObject_CallObject(getNameFunc, args);
     PyObject *klass = PyObject_CallObject(getClassFunc, args);
     
     if (!klass) {
       std::cout << "pyloader: No class object for type" << std::endl;
       continue;
     }
     
     char *tn = PyString_AsString(pname);
     
     if (!reg->hasType(tn)) {
       if (mFactory->addType(tn, klass)) {
         registerType(tn, mFactory, reg);
       } else {
         std::cout << "pyloader: Invalid type \"" << tn << "\"" << std::endl;
       }
     } else {
       std::cout << "pyloader: Type \"" << tn << "\" already registered" << std::endl;
     }
     
     Py_DECREF(pname);
     Py_DECREF(klass);
   }
   
   Py_DECREF(args);
   Py_DECREF(getCountFunc);
   Py_DECREF(getNameFunc);
   Py_DECREF(getClassFunc);
   
   mPyModules.push_back(mod);
 }
Example #28
0
int main(int argc, char *argv[]) {
   
//   system("python main.py");

   PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;

   if (argc != 3)
   {
       printf("Usage: exe_name python_source function_name\n");
       return 1;
   }

   // Initialize the Python Interpreter
   Py_Initialize();

   // Build the name object
   pName = PyString_FromString(argv[1]);

   std::cout << argv[1] << std::endl;

   PyRun_SimpleString("import sys");
   PyRun_SimpleString("import os");
   PyRun_SimpleString("print os.getcwd()");
   PyRun_SimpleString("sys.path.append(os.getcwd())");

   std::cout << "huh?" << std::endl;

   // Load the module object
   pModule = PyImport_Import(pName);

   // pDict is a borrowed reference
   pDict = PyModule_GetDict(pModule);

   // TODO: Verify module syntax better, otherwise this step can easily fail due to e.g.
   //
   // FAILS: ./executable my/module myFunc (should be my.module)
   // FAILS: No __init__.py in my/ folder

   // pFunc is also a borrowed reference
   pFunc = PyDict_GetItemString(pDict, argv[2]);

    // Process extra parameters
//    pArgs = PyTuple_New(1); //argc - 3);
//    for (int i=0; i < argc-3; i++) {
//       pValue = PyInt_FromLong(atoi(argv[i + 3]));
//
//       if (!pValue) {
//          PyErr_Print(); return 1; }
//
//       PyTuple_SetItem(pArgs, i, pValue);
//    }

   pArgs = 0;

   if (PyCallable_Check(pFunc)) {
      pValue = PyObject_CallObject(pFunc, pArgs);
   }
   else {
       PyErr_Print();
       Py_DECREF(pValue);
   }

   // Clean up
   Py_DECREF(pModule);
   Py_DECREF(pName);
//   Py_DECREF(pArgs); // Only needed if it is indeed used

   // Finish the Python Interpreter
   Py_Finalize();

   return 0;
}
/*!
 * @brief Prepare the session for use, including all the resources that are embedded.
 */
VOID python_prepare_session()
{
	Py_IgnoreEnvironmentFlag = 1;
	Py_NoSiteFlag = 1;
	Py_Initialize();
	PyEval_InitThreads();

	PyObject* stdoutModule = Py_InitModule("meterpreter_stdout", meterpreter_stdout_hooks);

	if (stdoutModule != NULL && PySys_SetObject("stdout", stdoutModule) == 0)
	{
		dprintf("[PYTHON] Successfully set the stdout hook");
	}
	else
	{
		dprintf("[PYTHON] Failed to set the stdout hook");
	}

	PyObject* stderrModule = Py_InitModule("meterpreter_stderr", meterpreter_stderr_hooks);
	if (stderrModule != NULL && PySys_SetObject("stderr", stderrModule) == 0)
	{
		dprintf("[PYTHON] Successfully set the stderr hook");
	}
	else
	{
		dprintf("[PYTHON] Failed to set the stderr hook");
	}

	// with the output handlers sorted, we load the stuff from the compressed resource
	// which should give us all the stuff we need to be useful.
	initerrno();
	initnt();
	init_socket();
	init_functools();
	
	// have we loaded the core pointer already?
	if (coreLibPointer == NULL)
	{
		MEMORY_BASIC_INFORMATION mbi;
		if (!VirtualQuery((LPVOID)python_prepare_session, &mbi, sizeof(mbi)))
		{
			dprintf("[PYTHON] VirtualQuery failed: %d", GetLastError());
			return;
		}

		HMODULE mod = (HMODULE)mbi.AllocationBase;
		dprintf("[PYTHON] Module handle: %p", (LPVOID)mod);

		HRSRC res = FindResource(mod, MAKEINTRESOURCEA(IDR_PYTHON_CORE), "BINARY");
		if (res == NULL)
		{
			dprintf("[PYTHON] Unable to find resource: %d", GetLastError());
			return;
		}

		HGLOBAL file = LoadResource(mod, res);

		if (file == NULL)
		{
			dprintf("[PYTHON] Unable to load core library resource: %d", GetLastError());
			return;
		}

		// store these pointers for when we reset the session, saves us from
		// doing all of this nonsense again.
		coreLibPointer = (LPBYTE)LockResource(file);
		coreLibSize = *(LPDWORD)coreLibPointer;
		coreLibPointer += sizeof(DWORD);
	}

	dprintf("[PYTHON] coreLibPointer: %p, coreLibSize: %d", coreLibPointer, coreLibSize);

	if (coreLibPointer != NULL)
	{
		// Create a byte array with everything in it
		PyObject* libString = PyString_FromStringAndSize(coreLibPointer, coreLibSize);
		dprintf("[PYTHON] libString is %p", libString);

		// import zlib
		PyObject* zlibModStr = PyString_FromString("zlib");
		dprintf("[PYTHON] zlibModStr: %p", zlibModStr);
		PyObject* zlibMod = PyImport_Import(zlibModStr);
		dprintf("[PYTHON] zlibMod: %p", zlibMod);
		// get a reference to the decompress function
		PyObject* zlibDecompress = PyObject_GetAttrString(zlibMod, "decompress");
		dprintf("[PYTHON] zlibDecompress: %p", zlibDecompress);
		// prepare arguments for invocation
		PyObject* zlibDecompressArgs = PyTuple_Pack(1, libString);
		dprintf("[PYTHON] zlibDecompressArgs: %p", zlibDecompressArgs);
		// call zlib.decompress(libString)
		PyObject* zlibDecompressResult = PyObject_CallObject(zlibDecompress, zlibDecompressArgs);
		dprintf("[PYTHON] zlibDecompressResult: %p", zlibDecompressResult);
		//dprintf("[PYTHON] zlibDecompressResult type: %s", zlibDecompressResult->ob_type->tp_name);

		PCHAR byteArray = NULL;
		Py_ssize_t byteArrayLength = 0;
		PyString_AsStringAndSize(zlibDecompressResult, &byteArray, &byteArrayLength);
		dprintf("[PYTHON] bytes: %p %u", byteArray, byteArrayLength);

		PyObject* modData = PyMarshal_ReadObjectFromString(byteArray, byteArrayLength);
		dprintf("[PYTHON] modData: %p", modData);

		PyObject* mainMod = PyImport_AddModule("__main__");
		PyObject* mainDict = PyModule_GetDict(mainMod);
		PyModule_AddObject(mainMod, "met_lib_data", modData);
		// TODO: double-check that we don't need to remove existing finders which might
		// hit the file system
#ifdef DEBUGTRACE
		PyRun_SimpleString("eval(met_lib_data[0]);met_init(True)");
#else
		PyRun_SimpleString("eval(met_lib_data[0]);met_init(False)");
#endif

		// TODO: figure out which reference counts need to be reduce to avoid leaking.
	}

	// now load the baked-in modules
	PyErr_Clear();
	for (InitFunc* f = &init_funcs[0]; f->func != NULL; f += 1)
	{
		dprintf("[PYTHON] Running %s", f->name);
		f->func();
		if (PyErr_Occurred())
		{
#ifdef DEBUGTRACE
			PyErr_Print();
#endif
			dprintf("[PYTHON] %s errored", f->name);
			PyErr_Clear();
		}
	}

	initialize_std_handlers();
	binding_init();
}
  int NRELPythonApplicInterface::derived_map_ac(const Dakota::String& ac_name)
  {
    printf ("entered python:derived_map_ac\n");

  // probably need to convert all of the following with SWIG or Boost!!
  // (there is minimal error checking for now)
  // need to cleanup ref counts on Python objects
  int fail_code = 0;

  // probably want to load the modules and functions at construction time, incl.
  // validation and store the objects for later, but need to resolve use of
  // analysisDriverIndex

  // for now we presume a single analysis component containing module:function
  const std::string& an_comp = analysisComponents[analysisDriverIndex][0];
  size_t pos = an_comp.find(":");
  std::string module_name = an_comp.substr(0,pos);
  std::string function_name = an_comp.substr(pos+1);

  printf ("importing the module %s\n", module_name.c_str());
  // import the module and function and test for callable
  PyObject *pModule = PyImport_Import(PyString_FromString(module_name.c_str()));
  if (pModule == NULL) {
    Cerr << "Error (Direct:Python): Failure importing module " << module_name 
	 << ".\n                       Consider setting PYTHONPATH."
	 << std::endl;
    abort_handler(-1);
  }
  printf ("imported the module\n");

  // Microsoft compiler chokes on this:
  //  char fn[function_name.size()+1];
  char *fn = new char[function_name.size()+1];
  strcpy(fn, function_name.c_str());
  PyObject *pFunc = PyObject_GetAttrString(pModule, fn);
  if (!pFunc || !PyCallable_Check(pFunc)) {
    Cerr << "Error (Direct:Python): Function " << function_name  << "not found "
	 << "or not callable" << std::endl;
    abort_handler(-1);
  }
  delete fn;

  // must use empty tuple here to pass to function taking only kwargs
  PyObject *pArgs = PyTuple_New(0);
  PyObject *pDict = PyDict_New();

  // convert DAKOTA data types to Python objects (lists and/or numpy arrays)
  PyObject *cv, *cv_labels, *div, *div_labels, *drv, *drv_labels,
    *av, *av_labels, *asv, *dvv;
  python_convert(xC, &cv);
  python_convert(xCLabels, &cv_labels);
  python_convert_int(xDI, xDI.length(), &div);
  python_convert(xDILabels, &div_labels);
  python_convert(xDR, &drv);
  python_convert(xDRLabels, &drv_labels);
  python_convert(xC, xDI, xDR, &av);
  python_convert(xCLabels, xDILabels, xDRLabels, &av_labels);
  python_convert_int(directFnASV, directFnASV.size(), &asv);
  python_convert_int(directFnDVV, directFnASV.size(), &dvv);
  // TO DO: analysis components

  // assemble everything into a dictionary to pass to user function
  // this should eat references to the objects declared above
  PyDict_SetItem(pDict, PyString_FromString("variables"), 
		 PyInt_FromLong((long) numVars));
  PyDict_SetItem(pDict, PyString_FromString("functions"), 
		 PyInt_FromLong((long) numFns)); 
  PyDict_SetItem(pDict, PyString_FromString("cv"), cv);
  PyDict_SetItem(pDict, PyString_FromString("cv_labels"), cv_labels);
  PyDict_SetItem(pDict, PyString_FromString("div"), div);
  PyDict_SetItem(pDict, PyString_FromString("div_labels"), div_labels);
  PyDict_SetItem(pDict, PyString_FromString("drv"), drv);
  PyDict_SetItem(pDict, PyString_FromString("drv_labels"), drv_labels);
  PyDict_SetItem(pDict, PyString_FromString("av"), av);
  PyDict_SetItem(pDict, PyString_FromString("av_labels"), av_labels);
  PyDict_SetItem(pDict, PyString_FromString("asv"), asv);
  PyDict_SetItem(pDict, PyString_FromString("dvv"), dvv);
  // Does not appear to exist in Windows version of Dakota, and I don't recall using it:
  //  PyDict_SetItem(pDict, PyString_FromString("fnEvalId"), 
  //		 PyInt_FromLong((long) fnEvalId)); 

  ///////
  ///PyDict_SetItem(pDict, PyString_FromString("data"), gData); 
  printf ("I have data at : %lx,   NOW WHAT do I do!?\n",  pUserData); 
  ///////
  bp::object * tmp2 = NULL;
  if (pUserData != NULL)
    {
      printf ("Setting raw PyObject in dict\n");
      tmp2 = (bp::object*)pUserData;
      PyDict_SetItem(pDict, PyString_FromString("user_data"), 
		     tmp2->ptr());
    }
  else
    printf("no data\n");


  // perform analysis
  if (outputLevel > NORMAL_OUTPUT)
    Cout << "Info (Direct:Python): Calling function " << function_name 
	 << " in module " << module_name << "." << std::endl;
  PyObject *retVal = PyObject_Call(pFunc, pArgs, pDict);
  Py_DECREF(pDict);
  Py_DECREF(pArgs);    
  Py_DECREF(pFunc);
  Py_DECREF(pModule);
  if (!retVal) {
    // TODO: better error reporting from Python
    Cerr << "Error (Direct:Python): Unknown error evaluating python "
	 << "function." << std::endl;
    abort_handler(-1);
  }
      
  bool fn_flag = false;
  for (int i=0; i<numFns; ++i)
    if (directFnASV[i] & 1) {
      fn_flag = true;
      break;
    }

  // process return type as dictionary, else assume list of functions only
  if (PyDict_Check(retVal)) {
    // or the user may return a dictionary containing entires fns, fnGrads,
    // fnHessians, fnLabels, failure (int)
    // fnGrads, e.g. is a list of lists of doubles
    // this is where Boost or SWIG could really help
    // making a lot of assumptions on types being returned
    PyObject *obj;
    if (fn_flag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fns")) ) {
	Cerr << "Python dictionary must contain list 'fns'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnVals, numFns)) {
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    if (gradFlag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fnGrads")) ) {
	Cerr << "Python dictionary must contain list 'fnGrads'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnGrads)) {
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    if (hessFlag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fnHessians")) ) {
	Cerr << "Python dictionary must contain list 'fnHessians'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnHessians)){
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    // optional returns
    if (obj = PyDict_GetItemString(retVal, "failure"))
      fail_code = PyInt_AsLong(obj);

    if (obj = PyDict_GetItemString(retVal, "fnLabels")) {
      if (!PyList_Check(obj) || PyList_Size(obj) != numFns) {
	Cerr << "'fnLabels' must be list of length numFns." << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      for (int i=0; i<numFns; ++i)
	fnLabels[i] = PyString_AsString(PyList_GetItem(obj, i));
    }
  }
  else {
    // asssume list/numpy array containing only functions
    if (fn_flag)
      python_convert(retVal, fnVals, numFns);
  }
  Py_DECREF(retVal);

  return(fail_code);    
  }