Dynamically linking python into my vc project - help required

mrinalini at edss.co.in mrinalini at edss.co.in
Wed Aug 3 04:58:48 EDT 2011


 Hi,

 I am trying to embed python into my MFC application. I have done this 
 before by statically linking to the python lib. But I want to change 
 this now.
 The idea is to take the information from the registry for the installed 
 version of python on the target machine. Then load python using 
 loadlibrary call and use the functions from python using pointers to 
 functions returned by GetProcAddress .

 For example -

        hModPython = AfxLoadLibrary("Python23.dll");

 	pFnPyRun_SimpleString *pFunction = NULL;
 	pFnPy_Initialize *pPy_Initialize = NULL;

 	pFunction = (pFnPyRun_SimpleString *)::GetProcAddress(hModPython, 
 "PyRun_SimpleString");
 	pPy_Initialize = (pFnPy_Initialize *)::GetProcAddress(hModPython, 
 "Py_Initialize");

 	try
 	{
 		pPy_Initialize();

 		if ( pFunction )
 		{
 			(*pFunction)("import sys");		// call the code
 		}
 		else
 		{
 			AfxMessageBox("unable to access function from python23.dll.", 
 MB_ICONSTOP|MB_OK);
 		}
 	}
 	catch(...)
 	{

 	}

 And then I want to execute a python script through my MFC application  
 -

         HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, 
 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

 	DWORD dwSize = GetFileSize(hFile, NULL);
 	DWORD dwRead;

 	char *s = new char[dwSize +1];

 	ReadFile(hFile, s, dwSize, &dwRead, NULL);

 	s[dwSize] = '\0';

 	CString wholefile(s);

 	wholefile.Remove('\r');
 	wholefile+="\n";
 	CloseHandle(hFile);

 	pFnPy_CompileString *pFPy_CompileString = (pFnPy_CompileString 
 *)::GetProcAddress(hModPython, "Py_CompileString");

 	CString fl(file);

 	PyObject* pCodeObject = pFPy_CompileString(wholefile.GetBuffer(0), 
 fl.GetBuffer(0), Py_file_input);

 	if (pCodeObject != NULL)
 	{
 		pFnPyEval_EvalCode *pFPyEval_EvalCode = (pFnPyEval_EvalCode 
 *)::GetProcAddress(hModPython, "PyEval_EvalCode");

 		PyObject* pObject = pFPyEval_EvalCode((PyCodeObject*)pCodeObject, 
 m_Dictionary, m_Dictionary);
 	}


 I am facing two problems here , though I want to link to python 
 dynamically I am required to include 	python.h for my code to compile 
 the following declaration.

 PyObject* pCodeObject



 I tried copying some of the python definitions including  PyObject into 
 a header in my mfc app. Then it complies fine. but Py_CompileString call 
 fails. so finally I am unable to run script from my MFC application by 
 linking to python dynamically.

 How can this be done ? Please help. Is there a different approach to 
 linking to python dynamically. Please could you write to me ?

 Thanks in advance,
 Mrinalini





More information about the Python-list mailing list