Python对象的本地C指针问题,怎么解决

 我来答
育知同创教育
2017-11-25 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
展开全部
Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer.
So this is my class:
class CGEGameModeBase
{
public:
virtual void FunctionCall()=0;
virtual const char* StringReturn()=0;
};

class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper<CGEPYGameMode>
{
public:
virtual void FunctionCall()
{
if (override f = this->get_override("FunctionCall"))
f();
}

virtual const char* StringReturn()
{
if (override f = this->get_override("StringReturn"))
return f();

return "FAILED TO CALL";
}
};

Boost wrapping:
BOOST_PYTHON_MODULE(GEGameMode)
{
class_<CGEGameModeBase, boost::noncopyable>("CGEGameModeBase", no_init);

class_<CGEPYGameMode, bases<CGEGameModeBase> >("CGEPYGameMode", no_init)
.def("FunctionCall", &CGEPYGameMode::FunctionCall)
.def("StringReturn", &CGEPYGameMode::StringReturn);
}

and the python code:
import GEGameMode

def Ident():
return "Alpha"

def NewGamePlay():
return "NewAlpha"

def NewAlpha():
import GEGameMode
import GEUtil

class Alpha(GEGameMode.CGEPYGameMode):
def __init__(self):
print "Made new Alpha!"

def FunctionCall(self):
GEUtil.Msg("This is function test Alpha!")

def StringReturn(self):
return "This is return test Alpha!"

return Alpha()

Now i can call the first to functions fine by doing this:
const char* ident = extract< const char* >( GetLocalDict()["Ident"]() );
const char* newgameplay = extract< const char* >( GetLocalDict()["NewGamePlay"]() );

printf("Loading Script: %s\n", ident);
CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( GetLocalDict()[newgameplay]() );

However when i try and convert the Alpha class back to its base class (last line above) i get an boost error:
TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha

I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?
Thanks to Stefan from the python c++ mailling list, i was missing
super(Alpha, self).__init__()

from the constructor call meaning it never made the parent class. Thought this would of been automatic :D
Only other issue i had was saving the new class instance as a global var otherwise it got cleaned up as it went out of scope.
So happy now
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式