3

I am working in an existing c++ project that builds a dll. I am trying to call python using the C api. I can either use #include <boost/python.hpp> or just #include <Python.h> and my code works fine.

I have pointed the linker at the folder containing python27.lib (MyProject -> Properties -> ConfigurationProerties -> Linker -> General -> Additional Library Directories) and so I am expecting it to statically link to python.

My problem is that when I look using Dependency Walker, I see that my dll is depending on python27.dll.

This is a case where I genuinely want to static link to python.

I have done a lot of research and tried various preprocessor directives but no luck. Thank you for any help

davidism
  • 121,510
  • 29
  • 395
  • 339
Peter A
  • 227
  • 1
  • 9
  • Does Python provide static library? If not, no way to do it – Matt Sep 10 '15 at 18:12
  • Yes I can see the python27.lib file and pointed the linker at its directory. – Peter A Sep 10 '15 at 18:31
  • File with extension lib doesn't mean it is a static lib file – Matt Sep 10 '15 at 18:35
  • Do you mean the .lib files are probably just stubs as in this answer http://stackoverflow.com/questions/1297013/why-do-we-still-need-a-lib-stub-file-when-weve-got-the-actual-dll-implementat ? Thank you – Peter A Sep 10 '15 at 22:54
  • yes. If DLL is also generated with the lib file – Matt Sep 11 '15 at 01:14

1 Answers1

2

Resolved as follows:

As pointed out by Matt, the lib files shipped with Python are not static libraries but just stub files.

Therefore I downloaded the python source and built it. To make my project link I had to:

  1. In the python project and all its dependencies, change Properties -> General -> ConfigurationType to Static library. For the executables (make_buildinfo and make_versioninfo), need to first build as executables once to get the .exe, and then build as static libraries to get the .lib files.
  2. Do this: Compiling Python to a static lib and using pythoncore.lib
  3. Set the preprocessor macro Py_NO_ENABLE_SHARED (make sure Py_ENABLE_SHARED is not set)
  4. Copy pyconfig.h into the Python Include directory
  5. Use the pure Python C API (give up using Boost Python, because it is dynamic linking to Python)
  6. Add these lines into the cpp file before calling Py_Initialize():

    // These (or a subset of them) are necessary so that it uses the static linked python, and does not try to load python from a default location. Py_NoSiteFlag = 1; Py_FrozenFlag = 1; Py_IgnoreEnvironmentFlag = 1; Py_SetPythonHome(""); Py_SetProgramName("");

  7. For 64 bit compilation, need to set Project Settings -> Configuration Properties -> Librarian -> General -> Target Machine for each project. Note that lib files get put in PCbuild\amd64 (not PCbuild)

Thank you

Community
  • 1
  • 1
Peter A
  • 227
  • 1
  • 9