Python nesting in C - Distribution
I have included python in a C application on Windows. To distribute, I put the whole python folder next to my exe:
\Installation Dir
app.exe
script.py
\python
As a test, I've simplified application C very much. It installs the interpreter and tries to start script.py
.
Here is all the content of the C source:
#include <Python.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
Py_OptimizeFlag=1;
Py_SetPythonHome("python");
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetPath("python/Lib;python/DLLs;python/Lib/site-packages;");
PySys_SetArgv(argc, argv);
PyObject* PyFileObject = PyFile_FromString("script.py", "r");
PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "script.py", 1);
Py_Finalize();
}
It seems to work well ... sometimes. On some machines, I get errors ImportError: DLL load failed
usually referring to _socket
.
I have explicitly set the folder path Lib
and DLLs
so I don't understand why I am getting this error?
It must be some kind of conflict with an existing version of Python, but have I successfully installed it to run on another PC with versions of python already installed?
Are there any other variables or registry settings I need to set to ensure that the built-in python can find what it needs?
Ideally, I would avoid setting registry values as I want this installation to be "standalone" and not potentially stub out any other version of python the user might install.
Any ideas?
source to share
Searching for a keyword: "_socket" in my python folder, I found something interesting. In the "python / libs" folder there are "_socket.lib" and "_socket.pyd" in the "python / DLL" folder. I don't know any details about this particular library, but I think you can solve your problem simply by adding "python / libs" to the line you set PySys_SetPath . Or you can try to include more folders by specifying sys.path in your own "everything is OK" environment.
The reason for this conjecture is that I have heard that .pyd files basically play the same role as DLL files when you program in C / C ++. When you compile a dynamic link library, you generate .h, .dll, and .lib files at the same time. The .dll file contains the main code and the .lib contains what the dll is exported.
source to share