環境:
WinXP-SP3(chs) + VS2010-SP1(en-us) + boost 1.47.0 + python 2.7(ActivePython2.7 攜帶)
boost編譯時,boost::python庫編譯為 stage debug release link=static runtime-link=shared
問題1:
python27 不認dll作為extension
解決方案:
project的output file 和 extension 都設置為 .pyd
問題2:
需要在導出類函數時,支持帶指針的參數 (重頭戲)
解決方案:
這個問題似乎網上沒有一個完整的答案,零零碎碎的問題有一堆,但感覺都不到位,接下來我就給個方案吧。(我對boost::python也不熟,如有錯誤希望好言指正:) )
1 #include <boost/python.hpp>
2 #include <stdio.h>
3 using namespace boost::python;
4
5 struct World
6 {
7 void simpleHello(void)
8 {
9 printf("this is simple hello\n");
10 }
11 void hello(int *data)
12 {
13 printf("World say hello :%d\n", *data);
14 }
15 int* ready(void)
16 {
17 return new int(1234);
18 }
19 };
20
21 BOOST_PYTHON_MODULE(sample)
22 {
23 class_<World>("World")
24 .def("simpleHello", &World::simpleHello)
25 .def("hello", &World::hello, arg("data"))
26 .def("ready", &World::ready, return_value_policy<return_opaque_pointer>())
27 ;
28 }
這里要說明二點:
1)這個例子既有傳指針參數,又有返回指針對象,算是把boost::python兩個典型問題囊括了。
2)return_opaque_pointer 是我查官方文檔后得到的一個變通(官方推薦這里用 manage_new_object,但不管你編不編的過,反正我是編不過,在翻了Reference manual后看到了 opaque_pointer,看名字覺得有戲,就拿來用了。貌似opaque_pointer的嚴格性更低一點。編譯通過,運行OK,反正就這樣了)