2011-07-14 15 views
0

我已經編寫了一些庫,其中包含一些使用QT對象(如QVector,QColor等)的類,而不從它們繼承。現在我想讓這些對象(部分)可用於python。我第一次嘗試使用SIP,但是這個記錄很差,我甚至無法構建這個例子。現在我正在嘗試boost.python,它對於標準C++類很好。boost.python和qt

但是,一旦我開始包括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。

回答

1

你需要QtGui的QColor,而不僅僅是QtCore。

+0

是的,這是答案,非常感謝!我用$ {QT_LIBRARYS} 替換$ {QT_QTCORE_LIBRARY},並添加了包含($ {QT_USE_FILE})的集合(QT_USE_GUI TRUE) 。但爲什麼我可以編譯庫,甚至在另一個C++程序中使用它? – Felix

+0

@Felix:AFAIK,ELF共享庫可以鏈接到缺少的符號,然後期望在負載時提供。在嘗試加載.so之前,Python沒有加載QtGui符號,因此運行時出現錯誤。 –