环境准备:
1.编译boost库或单独编译boost.python的方法见http://blog.csdn.net/zhanhuai1/article/details/7232995
2.编译boost.python的动态链接库,并把boost_python-vc90-mt-1_48.dll复制到操作系统的system32文件夹里去。
用python调用C++代码:
1.在visual studio中新建Win32项目(项目名字为BoostPythonTest)——下一步——应用程序类型选择“DLL”并勾选“空项目”——完成
2.打开:项目——属性——配置属性——C/C++,在附加包含目录中添加$BOOSTDIR的路径和python安装目录下的include路径
3.打开:项目——属性——配置属性——链接器——输入,在附加依赖荐中添加boost_python-vc90-mt-1_48.lib(可从$BOOSTDIR/stage/lib中复制到其他目录下)和python安装目录下的libs/python27.lib
4.在项目中添加一个cpp文件World.cpp,在其中输入代码:
#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace std;
using namespace boost::python;
class __declspec(dllexport) World
{
public:
World( string s): msg( s) {}
void set( string s)
{
msg = s;
}
string greet()
{
return msg;
}
string msg;
};
BOOST_PYTHON_MODULE( BoostPythonTest)
{
class_<World>("World", init<std::string>())
.def("greet", &World::greet)
.def("set", &World::set);
}
5.生成——生成解决方案
6.到项目目录下找到刚刚生成的dll,复制到准备保存*.py文件的目录下,并把后缀名从dll改成pyd
7.在第6步中的pyd文件所在的目录下新建一个python文件test.py,输入以下代码:
from BoostPythonTest import *
a = World("abcdef")
print a.greet()
8.用python的IDLE打开test.py,按F5即可运行。
注意:
1.World.cpp中的__declspec(dllexport)不要也没关系
2.BOOST_PYTHON_MODULE( BoostPythonTest)中的模块名必须和生成的dll同名,或者在生成dll之后对dll进行重命名,总之,模块名和dll名必须相同
3.不要忘记环境准备的第2条,如果没有复制该dll,会在运行test.py时报错“ImportError: DLL load failed: 找不到指定的模块。”