put, pdict, pdict);
6. int PyArg_Parse( PyObject *args, char *format, ...)
解构Python数据为C的类型,这样C程序中才可以使用Python里的数据。例:
/* convert to C and print it*/
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
7. PyObject* PyObject_GetAttrString( PyObject *o, char *attr_name)
返回模块对象o中的attr_name 属性或函数,相当于Python中表达式语句:o.attr_name。例:
/* to call mymod.transform(mymod.message) */
pfunc = PyObject_GetAttrString(pmod, "transform");
8. PyObject* Py_BuildValue( char *format, ...)
构建一个参数列表,把C类型转换为Python对象,使Python可以使用C类型数据,例:
cstr="this is hjs''''s test, to uppercase";
pargs = Py_BuildValue("(s)", cstr);
9. PyEval_CallObject(PyObject* pfunc, PyObject* pargs)
此函数有两个参数,都指向Python对象指针,pfunc是要调用的Python 函数,通常可用PyObject_GetAttrString()获得;pargs是函数的参数列表,通常可用Py_BuildValue()构建。例:
pstr = PyEval_CallObject(pfunc, pargs);
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
10. void Py_Finalize( )
关闭Python解释器,释放解释器所占用的资源。例:
Py_Finalize();
Python2.4环境没有提供调试版本的Python24d.lib,所以上述示例在release模式下编译。编译完成后,把可行文件和附2给出的mymod.py文件放在一起,再点击即可运行。为了简化编程,附3 给出了simplepy.h。这样,调用mymod.transform变成如下形式:
//#include”simplepy.h”
CSimplepy py;
py.ImportModule("mymod");
std::string str=py.CallObject("transform",
"this is hjs''''s test, to uppercase");
printf("%s\n", str.c_str());
接下来,我们来用C++为Python编写扩展模块(动态链接库),并在Python程序中调用C++开发的扩展功能函数。生成一个取名为pyUtil的Win32 DLL工程,除了pyUtil.cpp文件以外,从工程中移除所有其它文件,并填入如下的代码:
// pyUtil.cpp
#ifdef PYUTIL_EXPORTS
#define PYUTIL_API __declspec(dllexport)
#else
#define PYUTIL_API __declspec(dllimport)
#endif
#include<windows.h>
#include<string>
#include<Python.h>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
?)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
std::string Recognise_Img(const std::string url)
{
//返回结果
return "从dll中返回的数据... : " +url;
}
static PyObject* Recognise(PyObject *self, PyObject *args)
{
const char *url;
std::string sts;
if (!PyArg_ParseTuple(args, "s", &url))
return NULL;
sts = Recognise_Img(url);
return Py_BuildValue("s", sts.c_str() );
}
static PyMethodDef AllMyMethods[] = {
{"Recognise", Recognise, METH_VARARGS},//暴露给Python的函数
{NULL, NULL} /* Sentinel */
};
extern "C" PYUTIL_API void initpyUtil()
{
PyObject *m, *d;
m = Py_InitModul
|