<P>除了Booj.python(这可能是一个更友好的解决方案,它需要一个一对一的C++类到Python类的映射),可以在C++端提供一个C接口。这是许多解决方案中的一个,所以它有自己的折衷方案,但我将为那些不熟悉这项技术的人介绍它。对于完全公开,使用这种方法,一个不会连接C++到Python,而是C++到C到Python。下面我介绍了一个满足您的需求的例子,向您展示C++编译器的外部“C”设施的总体思路。</p>
<pre><code>//YourFile.cpp (compiled into a .dll or .so file)
#include <new> //For std::nothrow
//Either include a header defining your class, or define it here.
extern "C" //Tells the compile to use C-linkage for the next scope.
{
//Note: The interface this linkage region needs to use C only.
void * CreateInstanceOfClass( void )
{
// Note: Inside the function body, I can use C++.
return new(std::nothrow) MyClass;
}
//Thanks Chris.
void DeleteInstanceOfClass (void *ptr)
{
delete(std::nothrow) ptr;
}
int CallMemberTest(void *ptr)
{
// Note: A downside here is the lack of type safety.
// You could always internally(in the C++ library) save a reference to all
// pointers created of type MyClass and verify it is an element in that
//structure.
//
// Per comments with Andre, we should avoid throwing exceptions.
try
{
MyClass * ref = reinterpret_cast<MyClass *>(ptr);
return ref->Test();
}
catch(...)
{
return -1; //assuming -1 is an error condition.
}
}
} //End C linkage scope.
</code></pre>
<p>您可以使用</p>
<pre><code>gcc -shared -o test.so test.cpp
#creates test.so in your current working directory.
</code></pre>
<p>在python代码中,您可以这样做(显示2.7中的交互式提示):</p>
<pre><code>>>> from ctypes import cdll
>>> stdc=cdll.LoadLibrary("libc.so.6") # or similar to load c library
>>> stdcpp=cdll.LoadLibrary("libstdc++.so.6") # or similar to load c++ library
>>> myLib=cdll.LoadLibrary("/path/to/test.so")
>>> spam = myLib.CreateInstanceOfClass()
>>> spam
[outputs the pointer address of the element]
>>> value=CallMemberTest(spam)
[does whatever Test does to the spam reference of the object]
</code></pre>
<p>我相信Boost.Python在幕后也做了一些类似的工作,但是也许理解较低层次的概念是有帮助的。如果您试图访问C++库的功能,而不需要一对一映射,我会更感兴趣。</p>
<> P>关于C/C++交互的更多信息,请从Sun中查看这个页面:^ {A1}</P>