2012-11-18 28 views
0

我目前正試圖將一部分複雜程序放入動態庫中。這部分包含一些類,這些類也被boost python包裝到模塊中以再次嵌入。這裏是dll源代碼的簡化版本。在動態庫中提升python包裝未定義的參考

HELLO.CPP:

#include <boost/shared_ptr.hpp> 
#include <boost/make_shared.hpp> 
#include <boost/python.hpp> 
#include <Foo.h> 

using namespace boost::python; 

typedef boost::shared_ptr<Hello> hello_ptr; 

BOOST_PYTHON_MODULE(Hello) 
{ 
    class_<Hello, hello_ptr>("Hello") 
     .def("say_hello", &Hello::say_hello) 
    ; 
}; 


void Hello::say_hello(){ 
    cout << "Hello World!" << endl; 
} 

void World::foo(){ 
    Py_Initialize(); 

    try { 
     PyRun_SimpleString(
      "hello = None\n" 
      "\n" 
      "def setup(hello_from_cxx):\n" 
      " print 'setup called with', hello_from_cxx\n" 
      " global hello\n" 
      " hello = a_foo_from_cxx\n" 
      "\n" 
      "def run():\n" 
      " hello.say_hello()\n" 
      "\n" 
      "print 'main module loaded'\n" 
     ); 
     //initialize eviroment 
     initHello(); 

     hello_ptr hello = boost::make_shared<Hello>(); 

     object main = object(handle<>(borrowed(
      PyImport_AddModule("__main__") 
     ))); 

     // pass the reference to hello into python: 
     object setup_func = main.attr("setup"); 
     setup_func(hello); 

     // now run the python 'main' function 
     object run_func = main.attr("run"); 
     run_func(); 
    } 
    catch (error_already_set) { 
     PyErr_Print(); 
    } 
} 

Hello.h

#ifndef HELLO_H_INCLUDED 
#define HELLO_H_INCLUDED 

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

using namespace std; 

class Hello{ 
public: 
    void say_hello(); 
}; 

class World{ 
public: 
    void foo(); 
}; 

#endif // HELLO_H_INCLUDED 

在應用程序的主要功能我然後創建嵌入蟒蛇類的一個實例,但它提供了一個未定義的引用World :: foo(),即使該函數是在動態庫libFoo.dll中定義的,該庫也由主應用程序鏈接。

main.cpp中:

#include <iostream> 
#include <Hello.h> 

using namespace std; 

int main(){ 
    cout << "Test" << endl; 

    World world; 

    world.foo(); 
} 

控制檯:

undefined reference to `World::foo()' 

我使用的代碼:: Blocks的使用MinGW。

這個問題一直讓我覺得有些日子過去了,我似乎無法找到解決的辦法。希望您能夠幫助我。

在此先感謝。

UPDATE:

我現在試圖解決售後服務使用Python的C API此任務。有定義Python_Module(BOOST_PYTHON_MODULE())的步驟,該錯誤是絕對連接,通過定義像一個函數來完成:

PyMODINIT_FUNC initHello(void){ 
... 
} 

#define PyMODINIT_FUNC void 

現在寫盈解決錯誤。現在有誰有boost.python庫如何定義BOOST_PYTHON_MODULE函數嗎?也許也有這種解決方案?我在源文件中找不到任何PyMODINIT_FUNC。

回答

0

我自己找到了解決方案。

這就像我已經猜到了。需要的是像這樣定義BOOST_PYTHON_MODULE_INIT(名稱)。

# define BOOST_PYTHON_MODULE_INIT(name)        \ 
    void BOOST_PP_CAT(init_module_,name)();        \ 
extern "C" __attribute__ ((__visibility__("default"))) _BOOST_PYTHON_MODULE_INIT(name) 

其實我在一個頭文件中發現了一些#ifdef infront,但似乎它們不能正常工作。至少不適合我。