Posted on 2011-05-27 07:35
RTY 閱讀(253)
評論(0) 編輯 收藏 引用 所屬分類:
轉(zhuǎn)載隨筆
這是一個普通的混合使用方式, 但這種方式不能達到腳本真正的靈活性, c++每個屬性必須綁定一個唯一的set和get接口提供給python內(nèi)部訪問這個屬性
C/C++ code:
class sample
{
public:
int m_obj;
int GetValue(){
return m_obj;
}
void SetValue(int v){
m_obj= v;
}
};
class_<sample>("sample")
.add_property("m_obj", &sample::GetValue, &sample::SetValue )
我看過一個公司做的一個系統(tǒng)使用自己開發(fā)的python插件模塊實現(xiàn)了非常靈活的c++與python交互
這個系統(tǒng)有一個配置文件, 其中定義著一些屬性和接口, 在系統(tǒng)啟動時會去分析這些配置然后把它們
建立在python中, 用戶在python中對這些配置定義的屬性賦值都會被c++所截獲
下面是按照我的設(shè)想去做, 當(dāng)然下面代碼不能運行 因為不支持這樣的方式。
用戶在配置文件定義了3個屬性
int obj1, float obj2, string obj3
把它們綁定到一個通用的接口上
.add_property("obj1", &bind(&sample::GetValue, 1), &bind(&sample::SetValue, 1 ) )
.add_property("obj2", &bind(&sample::GetValue, 2), &bind(&sample::SetValue, 2 ) )
.add_property("obj3", &bind(&sample::GetValue, 3), &bind(&sample::SetValue, 3 ) )
class sample
{
public:
PyObject* m_objList;
int GetValue(int id);
void SetValue(int id, PyObject *val);
};
int sample::getValue( int id ){
return m_objList.find(id);
}
void sample::SetValue(int id, PyObject *val){
// 這里拿到被改變的數(shù)據(jù) 傳輸?shù)搅硪痪W(wǎng)絡(luò)上
...
// 將值賦給那個對象。
m_objList.find(id) = val;
}
這樣當(dāng)一個屬性被改變, c++就可以獲得所被改變的數(shù)據(jù), 然后做一些相關(guān)的邏輯處理, 比如將所改變的數(shù)據(jù)網(wǎng)絡(luò)傳輸?shù)搅硪欢藱C器上。
我查了很多資料 用boost都無法實現(xiàn)(也許我還沒了解), 所以來尋求一下大家的技術(shù)支持, 給一點建議。