Dynamically linking python into my vc project - help required

mrinalini at edss.co.in mrinalini at edss.co.in
Wed Aug 3 10:58:48 CEST 2011


 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, 
 	pPy_Initialize = (pFnPy_Initialize *)::GetProcAddress(hModPython, 


 		if ( pFunction )
 			(*pFunction)("import sys");		// call the code
 			AfxMessageBox("unable to access function from python23.dll.", 


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

         HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, 

 	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);


 	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,

More information about the Python-list mailing list