Search code examples
pythonc++python-3.xboost

Link a dll with a static library containing boost python import code causing the application to crash


I have created a static library containing a function used to import a module :

void callFn()
{
_putenv_s("PYTHONPATH", ".");
Py_Initialize();
namespace python = boost::python;
    try
    { 
        python::object my_python_class_module = python::import("pythonFile");

        python::object test = my_python_class_module.attr("Test")();

        test.attr("fn")("from c++");
    }
    catch (const python::error_already_set&)
    {
        PyErr_Print();
    }
}

Content of pythonFile.py:

class Test():
def fn(self,message):
print ("From python ")

I am calling this function(callFn()) from another x.dll used in an exe:

void ClassName::abc()
{
    callFn();      
}

Initially when I compiled x.dll, I got a linking error: LINK : fatal error LNK1104: cannot open file 'boost_python39-vc142-mt-x64-1_71.lib'

Then I built the boost source code to create boost_python39-vc142-mt-x64-1_71.lib. Doing this made the compilation successful, however on running the application, the application crashes giving an error:

Error loading library x - Cannot load library x: The specified module could not be found.

Please note, on commenting the 3 lines in "try" in callFn(), and repeating the above process does not crash the application. Any ideas why boost::python::import() causes application to crash?


Solution

  • You will get such error if any runtime dependency of x.dll is not satisfied.

    you are linking a shared library version of boost python and It is failing to dynamically load the boost python dll.

    You have 2 options to choose from.

    1. Compile a static version of boost python b2 link=static and link that.
    2. Put boost_python39-vc142-mt-x64-1_71.dll in the same folder as your library.