我试图通过PHP- cpp为PHP做一个Bencode扩展,所以有几个类,如:
class BItem : public Php::Base {
public:
virtual std::string getType() const {
return "BItem";
}
};
class BDict : public BItem {
public:
std::unordered_map<std::string, BItem*> BData;
std::string getType() const {
return "BDict";
}
Php::Value getItem(Php::Parameters ¶ms) {
std::string key = params[0];
...
...
return Php::Object(...);
}
// PHP: $a = new BDict(); $b = new BDict(); $a->addItem($b);
void addItem(Php::Parameters ¶ms) {
std::string key = params[0];
/**
* Here's the part confusing me
* Is there something like:
*/
BItem *toInsert = ¶ms[1]; // However, params[1] is actually a Php::Object
BData.insert({key, toInsert});
}
};
class BStr : public BItem {...};
class BList : public BItem {...};
class BInt : public BItem {...};
除BItem
外的所有类型都可以插入BDict
。
因此,在创建其中一个实例后,我如何将其传递回c++部分,"转换"回c++对象并最终将其插入BData
?
我是php扩展的新手,任何帮助或提示都将非常感谢。
根据Emiel的回答
void myFunction(Php::Parameters ¶ms)
{
// store the first parameter in a variable
Php::Value object = params[0];
// we want to be 100% sure that the passed in parameter is indeed one of our own objects
if (!object.instanceOf("MySpecialClass")) throw Php::Exception("Wrong parameter passed");
// cast the PHP object back into a C++ class
MySpecialClass *cppobject = (MySpecialClass *)object.implementation();
// @todo add your own code
}