Using Boost::Python::Object causes linker errors

隐身守侯 提交于 2020-01-03 01:21:47

问题


So, I'm attempting to embed Python into C++. I have gotten fairly far in, and have been able to do basic things like run strings of Python. As soon as I tried to use Boost::Python::Object I began getting these 4 linker errors.

I built boost using BJAM with Boost 1.54.0 and Python 2.7.5.

Python Lib Build Commands:

bootstrap
.\b2 toolset=msvc-10.0 --with-python

Minimal Code Example :

#include <boost/python.hpp>
#include <iostream>

int main(int, char **) 
{
    Py_Initialize();
    PyRun_SimpleString("import Entity");

    boost::python::object main_module = boost::python::import("__main__");
    boost::python::object main_namespace = main_module.attr("__dict__");

    Py_Finalize();

    std::cin.get();
    return 0;
}

Linker Errors:

1>PythonTest.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) class boost::python::api::object __cdecl boost::python::import(class boost::python::str)" (__imp_?import@python@boost@@YA?AVobject@api@12@Vstr@12@@Z) referenced in function _main
1>PythonTest.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) protected: __thiscall boost::python::detail::str_base::str_base(char const *)" (__imp_??0str_base@detail@python@boost@@IAE@PBD@Z) referenced in function "public: __thiscall boost::python::str::str(char const *)" (??0str@python@boost@@QAE@PBD@Z)
1>E:\Dev\PythonTest\Debug\PythonTest.exe : fatal error LNK1120: 2 unresolved externals

回答1:


Boost.Python can be built for static or dynamic linking. This is controlled by BOOST_PYTHON_STATIC_LIB being defined or not defined during the build process. The boost mailing list seems to indicate that this defintion and built-types are the result of some confusion.

When BOOST_PYTHON_STATIC_LIB is not defined, then Boost.Python assumes dynamic linkage. As a result, Boost.Python decorates symbol visibility for dllimport and dllexport. Based on the linker error, the example code was expecting to import the boost::python::import() function during linkage. If you have verified that the Boost.Python library is being linked, then the problem is likely the result of Boost.Python being built for static linkage, where the functions are not decorated for exporting. To resolve this, do one of the following:

  • Build Boost.Python for dynamic linkage (i.e. make sure BOOST_PYTHON_STATIC_LIB is not defined).
  • Define BOOST_PYTHON_STATIC_LIB when building the example code.
  • Define BOOST_PYTHON_STATIC_LIB in the example code before including boost/python.hpp.


来源:https://stackoverflow.com/questions/18058374/using-boostpythonobject-causes-linker-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!