【问题标题】:boost.python and qtboost.python 和 qt
【发布时间】:2011-07-14 14:26:12
【问题描述】:

我编写了一个库,其中包含一些使用 qt 对象的类,例如 QVector、QColor 等,而不从它们继承。现在我想让这些对象(部分)可用于 python。我第一次尝试 SIP,但是文档记录太差,我什至无法构建示例。现在我正在尝试 boost.python,它适用于标准 c++ 类。

但是,一旦我开始包含 Qt 的东西,它仍然可以编译,但无法导入到 python。这是一个最小的例子:

testclass.h

#include <QDebug>
#include <QVector>
#include <QColor>

class testclass
{
public:
    testclass();
    const char* output();
    QVector<double> & data();
    static int x(){return 1;}
    QColor * c();

private:
    QVector<double> v;
};
struct stat;

testclass.cpp

#include "testclass.h"

testclass::testclass()
{

}

const char* testclass::output()
{
    qDebug() << "string";
    return "hello";
}

QVector< double >& testclass::data()
{
    return v;
}

QColor* testclass::c()
{
    return new QColor();
}

testclassBoost.cpp

#include "testclass.h"
#include <boost/python.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(libtestclass)
{
    // Create the Python type object for our extension class and define __init__ function.
    class_<testclass>("testclass", init<>())
    .def("output", &testclass::output)  // Add a regular member function.
    ;
}

CMakeList.txt

project(boostpythontest)
cmake_minimum_required(VERSION 2.8)
find_package(Qt4 REQUIRED)

FIND_PACKAGE(Boost 1.45.0)
IF(Boost_FOUND)
  SET(Boost_USE_STATIC_LIBS OFF)
  SET(Boost_USE_MULTITHREADED ON)
  SET(Boost_USE_STATIC_RUNTIME OFF)
  FIND_PACKAGE(Boost 1.45.0 COMPONENTS python)
ELSEIF(NOT Boost_FOUND)
  MESSAGE(FATAL_ERROR "Unable to find correct Boost version. Did you set BOOST_ROOT?")
ENDIF()

include_directories(${QT_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR} ${Boost_INCLUDE_DIRS} "/usr/include/python2.7")


set(SRCS
  testclass.cpp
  testclassBoost.cpp
)

add_library(testclass SHARED ${SRCS})

target_link_libraries(testclass ${Boost_LIBRARIES} ${QT_QTCORE_LIBRARY})

现在尝试导入生成的库会导致以下错误:

Python 2.7.2 (default, Jun 27 2011, 14:59:25) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import libtestclass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./libtestclass.so: undefined symbol: _ZN6QColor10invalidateEv

有趣的是,一些 qt 类没有问题。没有函数 c() 它可以正常工作(QVector 没有问题)。我能做些什么来完成这项工作?我不打算在 python 中使用任何带有 qt 的函数,但我想在库的 c++ 部分中使用 qt。

【问题讨论】:

    标签: python qt boost


    【解决方案1】:

    QColor 需要 QtGui,而不仅仅是 QtCore。

    【讨论】:

    • 是的,这就是答案,非常感谢!我用 ${QT_LIBRARYS} 替换了 ${QT_QTCORE_LIBRARY} 并添加了 set(QT_USE_GUI TRUE) include(${QT_USE_FILE})。但是为什么我可以编译这个库,甚至在另一个 c++ 程序中使用它呢?
    • @Felix:AFAIK,ELF 共享库可以与缺少的符号链接,然后预计在加载时提供。 Python 在尝试加载您的 .so 之前没有加载 QtGui 符号,因此在运行时出错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多