python 调用C++模块 visual studio版

来源:互联网 发布:js验证日期格式 编辑:程序博客网 时间:2024/06/06 16:33

0. 安装python

貌似是废话,但这个必须要注意,同时要注意python的版本32 位还是64位

这里为$(python_install_dir)

 
1.编译boost python

1.1运行VC的编译环境工具

1.1 进入到boost 代码目录($(boost_src)下执行bootstrap.bat 生成 bjam

1.2  bjam toolset=msvc-12.0--build-type=complete --with-python

如果本机的python为64位必须带上 address-model=64

也就是

bjam toolset=msvc-12.0--build-type=complete --with-python  address-model=64

编译结束后,在stage\lib下生成相关的目录文件

$(boost_src)\stage\lib

 
2.创建一个DLL工程

2.1 include 问题

在VC的include dir中添加

$(python_install_dir)\include

$(boost_src)


2.2 lib 问题

在VC的lib dir中添加

$(python_install_dir)\libs

$(boost_src)\stage\lib


 

2.3 编译生成方式

一般来说,我们生成目标都希望一个独立的DLL,所以最好要把编译项调成 /MT



但调成/MT 会被boost警告,甚至当错误

需要这就是需要在

#include <boost/python.hpp>
上面添加

#define  BOOST_PYTHON_STATIC_LIB

 

#define  BOOST_PYTHON_STATIC_LIB#include <boost/python.hpp>char const* greet(){    return "hello, world";}BOOST_PYTHON_MODULE(hello_ext){    using namespace boost::python;    def("greet", greet);}


2.4 python喜欢的

由于我们生成的东西是个DLL,而python认的是pyd, 所以需要把输出的后缀后改为pyd


 

2.5 注意事项

a.如果python是64位的话,DLL必要编译成64位)


 
3.调试

生成的pyd怎么测试呢?

一般来说,是需要将pyd 复制到 $(python_install_dir)\lib下,注意是lib 不是libs

这是官方说法

"

Yes, .pyd files are dll’s, but there are a fewdifferences. If you have a DLL named foo.pyd, then it must have afunction initfoo(). You can then write Python “importfoo”, and Python will search for foo.pyd (as well asfoo.py, foo.pyc) and if it finds it, will attempt tocall initfoo() to initialize it. You do not link your .exe withfoo.lib, as that would cause Windows to require the DLL to be present.

 

Note that the search path for foo.pyd isPYTHONPATH, not the same as the path that Windows uses to search for foo.dll.Also, foo.pyd need not be present to run your program, whereas if you linkedyour program with a dll, the dll is required. Of course, foo.pyd is required ifyou want to say import foo. In a DLL, linkage is declared in thesource code with __declspec(dllexport). In a .pyd, linkage is defined in alist of available functions.

"

 

为了能更好调试,需要:

a.

在degugging的Environment中

PYTHONPATH=$(OutputPath)

b.

在degugging的Working Directory中改为

$(python_install_dir)

c.

在degugging的Command中改为

python.exe

 

好了 F5

 

可以看到断点是无效的,因为我们的pyd还没加到进程中

import 后就OK了


调个函数


0 0
原创粉丝点击