|
|
Boost.PythonFrequently Asked Questions (FAQs)㣼뎊̢㨆AQ㩼/h2> |
*= operator
work?If what you're trying to do is something like this:
ȧ黃名ͼբѹ㺍
typedef boost::function<void (string s) > funcptr;
void foo(funcptr fp)
{
fp("hello,world!");
}
BOOST_PYTHON_MODULE(test)
{
def("foo",foo) ;
}
And then:
Ȼ곣ꍊ
>>> def hello(s): ... print s ... >>> foo(hello) hello, world!
The short answer is: "you can't". This is not a
Boost.Python limitation so much as a limitation of C++. The
problem is that a Python function is actually data, and the only
way of associating data with a C++ function pointer is to store it
in a static variable of the function. The problem with that is
that you can only associate one piece of data with every C++
function, and we have no way of compiling a new C++ function
on-the-fly for every Python function you decide to pass
to foo. In other words, this could work if the C++
function is always going to invoke the same Python
function, but you probably don't want that.
첶̵Ļشʇ㺡ᱡ㍊ բ⻊ǂoost.Python粲ޖƣ춸ʇC++粲ޖơ㍊ Ί̢ԚӚ㬐ythonꯊ톤ʵNJ㬍 渽늽ꏵ歸븶C++ꯊ햸ի載蒻罷裬 ʇ챣䦎꺯ʽ齉⌬ᤁ 渃︶C++ꯊ햻Ĝᣴ撻睊㬍 ⢇Ҏ҃ǎ莪y趴뵝踼code>foo儐ythonꯊ 촊ᵘ᠒뒻趐μă++ꯊ 뻾仰˵㬈繻C++ꯊ헜ʇ巔uem>ͬһ趼/em>Pythonꯊ ˼ܹ䗷㬵넇ܲ늇ģϫҪ儡㍊
If you have the luxury of changing the C++ code you're
wrapping, pass it an object instead and call that;
the overloaded function call operator will invoke the Python
function you pass it behind the object.
ȧ黃ㄜ輸Ą㒪碗ൄC++亂룬
Ď괫坒븶object⢵瓃˼㻍
֘Ԙ儺巔Oˋ㷻롵瓃ģ˹䫵ݵļcode>objectᳺ㵄Pythonꯊ
For more perspective on the issue, see this posting.
攓ڸO錢儸춠雵㣬ǫﴼa href="http://aspn.activestate.com/ASPN/Mail/Message/1554837">բ趌뗓.
That exception is protecting you from causing a nasty crash. It usually happens in response to some code like this:
胒쳣ʇ䄺aӚԬ㉎㏕儱