e("pyUtil", AllMyMethods); //初始化本模块,并暴露函数
d = PyModule_GetDict(m);
}
在Python代码中调用这个动态链接库:
import pyUtil
result = pyUtil.Recognise("input url of specific data")
print "the result is: "+ result
用C++为Python写扩展时,如果您愿意使用Boost.Python库的话,开发过程会变得更开心J,要编写一个与上述pyUtil同样功能的动态链接库,只需把文件内容替换为下面的代码。当然,编译需要boost_python.lib支持,运行需要boost_python.dll支持。
#include<string>
#include <boost/python.hpp>
using namespace boost::python;
#pragma comment(lib, "boost_python.lib")
std::string strtmp;
char const* Recognise(const char* url)
{
strtmp ="从dll中返回的数据... : ";
strtmp+=url;
return strtmp.c_str();
}
BOOST_PYTHON_MODULE(pyUtil)
{
def("Recognise", Recognise);
}
所有示例都在Microsoft Windows XP Professional + Microsoft Visual Studio .NET 2003 + Python2.4环境下测试通过,本文所用的Boost库为1.33版本。
参考资料
[1] Python Documentation Release 2.4.1. 2005.3.30,如果您以默认方式安装了Python2.4,那么该文档的位置在C:\Program Files\Python24\Doc\Python24.chm;
[2] Michael Dawson. Python Programming for the Absolute Beginner. Premier Press. 2003;
[3] Mark Lutz. Programming Python, 2nd Edition. O''''Reilly. 2001.3 ;
[4] Mark Hammond, Andy Robinson. Python Programming on Win32. O''''Reilly. 2000.1 ;
Python主页:http://www.python.org;
Boost库主面:www.boost.org;
附1 text.txt
this is test text in text.txt.
附2 mymod.py
import string
message = ''''original string''''
message =message+message
msg_error=""
try:
text_file = open("text.txt", "r")
whole_thing = text_file.read()
print whole_thing
text_file.close()
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
def transform(input):
#input = string.replace(input, ''''life'''', ''''Python'''')
return string.upper(input)
def change_msg(nul):
global message #如果没有此行,message是函数里头的局部变量
message=''''string changed''''
return message
def r_file(nul):
return whole_thing
def get_msg(nul):
return message
附3 simplepy.h
#ifndef _SIMPLEPY_H_
#define _SIMPLEPY_H_
// simplepy.h v1.0
// Purpose: facilities for Embedded Python.
// by hujinshan @2005年9月2日9:13:02
#include
using std::string;
#include
//--------------------------------------------------------------------
// Purpose: ease the job to embed Python into C++ applications
// by hujinshan @2005年9月2日9:13:18
//--------------------------------------------------------------------
class CSimplepy // : private noncopyable
{
public:
///constructor
CSimplepy()
{
Py_Initialize();
pstr=NULL, pmod=NULL, pdict=NULL;
pfunc=NULL, pargs=NULL;
}
///destructor
virtual ~CSimplepy()
{
Py_Finalize();
}
///import the user module
bool ImportModule(const char* mod_name)
{
try{
|