If do want to use "python25_d.lib" and/or "python25_d.dll" to debug python scripts,
can use Visual C++ to compile python25 source code.
1. download python-2.5.4.tgz (11M) from python's official website:
http://www.python.org/ftp/python/2.5.4/Python-2.5.4.tgz
2. Unzipped and look for directory "python-2.5.4\PCbuild8\"
(Note that: directory ".\PCbuild\" is for VC 7.0)
Use VC++ 2005 (ver8.0) to open the pcbuild.sln under directory ".\PCbuild8\". You will see 20 projects. Build only two projects "python" and "pythoncore".
3. There will be two files "python25_d.lib" and "python25_d.dll" generated under directory ".\PCbuild8\win32debug". Copy them into "c:\python25\libs" and "c:\windows\system32"
respectively. Previously, "python25.dll" and "python25.lib" already there.
4. Turn on "debug" in VC and rebuild. Succeed.
However, I did not figure out how to use debug version in VC to debug into my python file.:-(
Note: Python's latest version is 2.6. But since I use "pylab/matplotlib" which currently only offers package ver0.98 for python2.5 under windows. So,... python2.5.4 is my choice.
2009/03/31
2009/03/29
C++和python的相互调用-II
编写扩展 Use python to write extension for C++ program
Visual C++ 2005 下创建新 Win32/ Win32 DLL project. 这样不用手写 *.def文件和手工编译链接。
然后将附带cpp文件做成 dll.
Python can only use this "*.dll" by changing it to "*.pyd".
Example:
1. Change the built "pyUtil.dll" to file name "pyUtil.pyd".
2. In python command line:
import sys
sys.path.append(".\\") # where pyUtil.pyd locates
# Or, put pyUtil.pyd file under python dll directory, "C:\Python25\DLLs".
# Note: "C:\Python25\libs" store static library like "pyUtil.lib".
import pyUtil
pyUtil.Recognise("ddddd")
C program can use python extension like static library.
That is: C program with pyUtil.py under the same directory,
which needs support of "C:\python25\libs\python25.lib".
C program can use this "*.dll" normally.
The usage is same as above.
Note that put pyUtil.dll under directory "c:\windows\system32\".
Source code for dll:
//////////////////////////////////////////////////////////////////
// pyUtil.cpp :
#ifdef _MANAGED
#pragma managed(push, off)
#endif
#include "stdafx.h"
#include "string.h"
#include "Python.h" // added
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
/*
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
*/
return TRUE;
}
/////////// my code
std::string Recognise_Img(const std::string url)
{ return "hello, " +url;
}
static PyObject* Recognise(PyObject *self, PyObject *args)
{
const char *url;
std::string sts;
if (!PyArg_ParseTuple(args, "s", &url)) // parse python objects from input
return NULL;
sts = Recognise_Img(url); // add your code here.
return Py_BuildValue("s", sts.c_str() ); // return python objects if used in python
}
static PyMethodDef AllMyMethods[] = { // declare of function list
{"Recognise", Recognise, METH_VARARGS}, // function name
{NULL, NULL} // need this to end decl
};
extern "C" PyMODINIT_FUNC initpyUtil() // initMyPythonModuleName
{
PyObject *m, *d;
m = Py_InitModule("pyUtil", AllMyMethods); // Module Name = file name
d = PyModule_GetDict(m);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
Visual C++ 2005 下创建新 Win32/ Win32 DLL project. 这样不用手写 *.def文件和手工编译链接。
然后将附带cpp文件做成 dll.
Python can only use this "*.dll" by changing it to "*.pyd".
Example:
1. Change the built "pyUtil.dll" to file name "pyUtil.pyd".
2. In python command line:
import sys
sys.path.append(".\\") # where pyUtil.pyd locates
# Or, put pyUtil.pyd file under python dll directory, "C:\Python25\DLLs".
# Note: "C:\Python25\libs" store static library like "pyUtil.lib".
import pyUtil
pyUtil.Recognise("ddddd")
C program can use python extension like static library.
That is: C program with pyUtil.py under the same directory,
which needs support of "C:\python25\libs\python25.lib".
C program can use this "*.dll" normally.
The usage is same as above.
Note that put pyUtil.dll under directory "c:\windows\system32\".
Source code for dll:
//////////////////////////////////////////////////////////////////
// pyUtil.cpp :
#ifdef _MANAGED
#pragma managed(push, off)
#endif
#include
#include "string.h"
#include
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
/*
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
*/
return TRUE;
}
/////////// my code
std::string Recognise_Img(const std::string url)
{ return "hello, " +url;
}
static PyObject* Recognise(PyObject *self, PyObject *args)
{
const char *url;
std::string sts;
if (!PyArg_ParseTuple(args, "s", &url)) // parse python objects from input
return NULL;
sts = Recognise_Img(url); // add your code here.
return Py_BuildValue("s", sts.c_str() ); // return python objects if used in python
}
static PyMethodDef AllMyMethods[] = { // declare of function list
{"Recognise", Recognise, METH_VARARGS}, // function name
{NULL, NULL} // need this to end decl
};
extern "C" PyMODINIT_FUNC initpyUtil() // initMyPythonModuleName
{
PyObject *m, *d;
m = Py_InitModule("pyUtil", AllMyMethods); // Module Name = file name
d = PyModule_GetDict(m);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
2009/03/23
C++扩展和嵌入Python
C++扩展和嵌入Python
作者:胡金山 来源:www.vckbase.com
Paper source
下载源代码
Python简介
Python是一种简单易学,功能强大的解释型编程语言,它有简洁明了的语法,高效率的高层数据结构,能够简单而有效地实现面向对象编程,特别适用于快速应用程序开发,也可以用来开发大规模的重要的商业应用。Python是一个理想的脚本语言。Python免费开源,可移植到多种操作系统,只要避免使用依赖于特定操作系统的特性,Python程序无需修改就可以在各种平台上面运行。
Python拥有现代编程语言所具有的一切强大功能,Python标准库十分庞大,可以帮助开发者处理各种工作,如:图形用户界面、文件处理、多媒体、正 则表达式、文档生成、单元测试、线程、数据库、网络通讯、网页浏览器、CGI、FTP、电子邮件、XML、HTML、WAV文件、密码系统、Tk和其他与 系统有关的操作。只要安装了Python,这些功能都是可用的除了标准库以外,还有许多其他高质量的库,如wxPython、Twisted和 Python图形库等等数不胜数。
Python容易扩展和嵌入。Python提供的许多标准模块支持C或者C++接口。Python和C可以一起工作,它可以嵌入到C或者C++的应用程序 当中,因此可用Python语言为应用程序提供脚本接口,由于支持跨语言开发,可用Python设计概念化应用程序,并逐步移植到C,使用前不必用C 重写应用程序。(Jython使Python可以和Java一起工作,使开发者可以在Python里面调Java的包,也可以在Java里面使用 Python的对象。还有更妙的,由于Jython的解释器完全用Java编写,因此可以在支持Java的任何平台上部署Python程序,甚至WEB浏 览器也可以直接运行Python脚本。)
提出问题
在某个C++应用程序中,我们用一组插件来实现一些具有统一接口的功能,我们使用Python来代替动态链接库形式的插件,这样可以方便地根据需求的变化 改写脚本代码,而不是必须重新编译链接二进制的动态链接库。Python强大的功能足以胜任,但是有一些操作系统特定的功能需要用C++来实现,再由 Python调用。所以,最基础地,我们需要做到:- 把Python嵌入到C++应用程序中,在C++程序中调用Python函数和获得变量的值;
- 用C++为Python编写扩展模块(动态链接库),在Python程序中调用C++开发的扩展功能函数。
常用的Python/C API介绍
下面是例子中用到的几个Python/C API的简要介绍及示例代码。注意,这并不是这些函数的详细介绍,而仅仅是我们所用到的功能简介,更详细内容请参考文档[1]、[2]、[3]、[4]。打开Microsoft Visual Studio .NET 2003,新建一个控制台程序
- #include
#include
并在main函数里加入示例代码。
- //先定义一些变量
- char *cstr;
- PyObject *pstr, *pmod, *pdict;
- PyObject *pfunc, *pargs;
//先定义一些变量 char *cstr; PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs;
1. void Py_Initialize( )
初始化Python解释器,在C++程序中使用其它Python/C API之前,必须调用此函数,如果调用失败,将产生一个致命的错误。例:- Py_Initialize();
Py_Initialize();
2. int PyRun_SimpleString( const char *command)
执行一段Python代码,就好象是在__main__ 函数里面执行一样。例:- PyRun_SimpleString("from time import time,ctime "
- "print ''Today is'',ctime(time()) ");
PyRun_SimpleString("from time import time,ctime " "print ''Today is'',ctime(time()) ");
3. PyObject* PyImport_ImportModule( char *name)
导入一个Python模块,参数name可以是*.py文件的文件名。相当于Python内建函数__import__()。例:- pmod = PyImport_ImportModule("mymod"); //mymod.py
pmod = PyImport_ImportModule("mymod"); //mymod.py
4. PyObject* PyModule_GetDict( PyObject *module)
相当于Python模块对象的__dict__ 属性,得到模块名称空间下的字典对象。例:- pdict = PyModule_GetDict(pmod);
pdict = PyModule_GetDict(pmod);
5. PyObject* PyRun_String( const char *str, int start, PyObject *globals, PyObject *locals)
执行一段Python代码。- pstr = PyRun_String("message", Py_eval_input, pdict, pdict);
pstr = PyRun_String("message", Py_eval_input, 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 ", cstr);
/* convert to C and print it*/ PyArg_Parse(pstr, "s", &cstr); printf("%s ", 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");
/* 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);
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 ", cstr);
pstr = PyEval_CallObject(pfunc, pargs); PyArg_Parse(pstr, "s", &cstr); printf("%s ", cstr);
10. void Py_Finalize( )
关闭Python解释器,释放解释器所占用的资源。例:- Py_Finalize();
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 ", str.c_str());
//#include”simplepy.h” CSimplepy py; py.ImportModule("mymod"); std::string str=py.CallObject("transform", "this is hjs''s test, to uppercase"); printf("%s ", 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
- #include
- #include
- 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_InitModule("pyUtil", AllMyMethods); //初始化本模块,并暴露函数
- d = PyModule_GetDict(m);
- }
// pyUtil.cpp #ifdef PYUTIL_EXPORTS #define PYUTIL_API __declspec(dllexport) #else #define PYUTIL_API __declspec(dllimport) #endif #include#include #include 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_InitModule("pyUtil", AllMyMethods); //初始化本模块,并暴露函数 d = PyModule_GetDict(m); }
在Python代码中调用这个动态链接库:
- import pyUtil
- result = pyUtil.Recognise("input url of specific data")
- print "the result is: "+ result
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
- #include
- 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);
- }
#include#include 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版本。
参考资料
- Python Documentation Release 2.4.1. 2005.3.30,如果您以默认方式安装了Python2.4,那么该文档的位置在C:\Program Files\Python24\Doc\Python24.chm;
- Michael Dawson. Python Programming for the Absolute Beginner. Premier Press. 2003;
- Mark Lutz. Programming Python, 2nd Edition. O''Reilly. 2001.3 ;
- Mark Hammond, Andy Robinson. Python Programming on Win32. O''Reilly. 2000.1 ;
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
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{
- pmod = PyImport_ImportModule(const_cast(mod_name));
- if(pmod==NULL)
- return false;
- pdict = PyModule_GetDict(pmod);
- }
- catch(...)
- {
- return false;
- }
- if(pmod!=NULL && pdict!=NULL)
- return true;
- else
- return false;
- }
- ///Executes the Python source code from command in the __main__ module.
- ///If __main__ does not already exist, it is created.
- ///Returns 0 on success or -1 if an exception was raised.
- ///If there was an error, there is no way to get the exception information.
- int Run_SimpleString(const char* str)
- {
- return PyRun_SimpleString(const_cast(str) );
- }
- ///PyRun_String("message", Py_eval_input, pdict, pdict);
- ///Execute Python source code from str in the context specified by the dictionaries globals.
- ///The parameter start specifies the start token that should be used to parse the source code.
- ///Returns the result of executing the code as a Python object, or NULL if an exception was raised.
- string Run_String(const char* str)
- {
- char *cstr;
- pstr = PyRun_String(str, Py_eval_input, pdict, pdict);
- if(pstr==NULL)
- throw ("when Run_String, there is an exception was raised by Python environment.");
- PyArg_Parse(pstr, "s", &cstr);
- return string(cstr);
- }
- ///support olny one parameter for python function, I think it''s just enough.
- string CallObject(const char* func_name, const char* parameter)
- {
- pfunc=NULL;
- pfunc = PyObject_GetAttrString(pmod, const_cast(func_name));
- if(pfunc==NULL)
- throw (string("do not found in Python module for: ")
- +func_name).c_str();
- char* cstr;
- pargs = Py_BuildValue("(s)", const_cast(parameter));
- pstr = PyEval_CallObject(pfunc, pargs);
- if(pstr==NULL)
- throw ("when PyEval_CallObject, there is an exception was raised by Python environment");
- PyArg_Parse(pstr, "s", &cstr);
- return string(cstr);
- }
- //PyObject *args;
- //args = Py_BuildValue("(si)", label, count); /* make arg-list */
- //pres = PyEval_CallObject(Handler, args);
- protected:
- PyObject *pstr, *pmod, *pdict;
- PyObject *pfunc, *pargs;
- };
- #endif // _SIMPLEPY_H_
- // end of file
#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{ pmod = PyImport_ImportModule(const_cast(mod_name)); if(pmod==NULL) return false; pdict = PyModule_GetDict(pmod); } catch(...) { return false; } if(pmod!=NULL && pdict!=NULL) return true; else return false; } ///Executes the Python source code from command in the __main__ module. ///If __main__ does not already exist, it is created. ///Returns 0 on success or -1 if an exception was raised. ///If there was an error, there is no way to get the exception information. int Run_SimpleString(const char* str) { return PyRun_SimpleString(const_cast(str) ); } ///PyRun_String("message", Py_eval_input, pdict, pdict); ///Execute Python source code from str in the context specified by the dictionaries globals. ///The parameter start specifies the start token that should be used to parse the source code. ///Returns the result of executing the code as a Python object, or NULL if an exception was raised. string Run_String(const char* str) { char *cstr; pstr = PyRun_String(str, Py_eval_input, pdict, pdict); if(pstr==NULL) throw ("when Run_String, there is an exception was raised by Python environment."); PyArg_Parse(pstr, "s", &cstr); return string(cstr); } ///support olny one parameter for python function, I think it''s just enough. string CallObject(const char* func_name, const char* parameter) { pfunc=NULL; pfunc = PyObject_GetAttrString(pmod, const_cast(func_name)); if(pfunc==NULL) throw (string("do not found in Python module for: ") +func_name).c_str(); char* cstr; pargs = Py_BuildValue("(s)", const_cast(parameter)); pstr = PyEval_CallObject(pfunc, pargs); if(pstr==NULL) throw ("when PyEval_CallObject, there is an exception was raised by Python environment"); PyArg_Parse(pstr, "s", &cstr); return string(cstr); } //PyObject *args; //args = Py_BuildValue("(si)", label, count); /* make arg-list */ //pres = PyEval_CallObject(Handler, args); protected: PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs; }; #endif // _SIMPLEPY_H_ // end of file
2009/03/20
C++和Python的相互调用
c++和python的互相调用
简单配置如下:
python安装目录: C:\Python26
头文件包含:
VStudio->Tools->Options->Directories->Include files 加入 C:\PYTHON26\INCLUDE
库文件包含:
VStudio->Tools->options->Directories->Library files 加入 C:\PYTHON26\LIBS
如果是debug版本,有可能会提示can't open file "python26_d.lib"没有调试版本的类库.
Solution: 把C:\Python26\libs\python26.lib复制一个python26_d.lib即可
否则直接用release版本就行; Or change python26_d.lib to python26.lib in "pyconfig.h" file, and comment "#define Py_DEBUG".
工程文件中包含了c++调用python中的函数,也同时把c++的函数做成了dll,以供python之调用;
所以也就发生另个一个问题,c++调用python时,最后关闭了python解释器
Py_Finalize(); 以至于python又调用dll时,发生错误;所以在生成dll时,注释掉
Py_Initialize();以及Py_Finalize();
若没有装VC,可以去微软网站下一个C++的编译器 VCTookitSetup.exe.
Under VC->VStudio Tools-> VStudio 2005 command prompt , 执行命令 cl cfile编译。
举例:
1、C中调用PYTHON
#include
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
直接用CL 文件名 编译就是
2、 PYTHON调用由C生成的DLL
C代码:如FOO.C
#include
/* Define the method table. */
static PyObject *foo_bar(PyObject *self, PyObject *args);
static PyMethodDef FooMethods[] = {
{"bar", foo_bar, METH_VARARGS},
{NULL, NULL}
};
/* Here's the initialization function. We don't need to do anything
for our own needs, but Python needs that method table. */
void initfoo()
{
(void) Py_InitModule("foo", FooMethods);
}
/* Finally, let's do something ... involved ... as an example function. */
static PyObject *foo_bar(PyObject *self, PyObject *args)
{
char *string;
int len;
if (!PyArg_ParseTuple(args, "s", &string))
return NULL;
len = strlen(string);
return Py_BuildValue("i", len);
}
C定义文件:foo.def
EXPORTS
initfoo
编译生成foo.dll
cl -c foo.c;
link foo.obj /dll /def:foo.def /OUT:foo.dll
将foo.dll 改名为 foo.pyd
在PYTHON中调用:
import foo
dir(foo)
…
即可以看到结果:
>>> import foo
>>> dir(foo)
['__doc__', '__file__', '__name__', 'bar']
>>> ^Z
为简化python使用C的数据类型,可以 import ctypes . it is better over pyrex .
3 C调用由python生成的dll
写一个C程序,该程序存放调用python的函数接口。然后将该C程序和python程序一起做成DLL即可。
主要参考
C++ 扩展和嵌入 Python
http://www.vckbase.com/document/viewdoc/?id=1540
简单配置如下:
python安装目录: C:\Python26
头文件包含:
VStudio->Tools->Options->Directories->Include files 加入 C:\PYTHON26\INCLUDE
库文件包含:
VStudio->Tools->options->Directories->Library files 加入 C:\PYTHON26\LIBS
如果是debug版本,有可能会提示can't open file "python26_d.lib"没有调试版本的类库.
Solution: 把C:\Python26\libs\python26.lib复制一个python26_d.lib即可
否则直接用release版本就行; Or change python26_d.lib to python26.lib in "pyconfig.h" file, and comment "#define Py_DEBUG".
工程文件中包含了c++调用python中的函数,也同时把c++的函数做成了dll,以供python之调用;
Py_Finalize(); 以至于python又调用dll时,发生错误;所以在生成dll时,注释掉
Py_Initialize();以及Py_Finalize();
若没有装VC,可以去微软网站下一个C++的编译器 VCTookitSetup.exe.
Under VC->VStudio Tools-> VStudio 2005 command prompt , 执行命令 cl cfile编译。
举例:
1、C中调用PYTHON
#include
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
直接用CL 文件名 编译就是
2、
C代码:如FOO.C
#include
/* Define the method table. */
static PyObject *foo_bar(PyObject *self, PyObject *args);
static PyMethodDef FooMethods[] = {
{"bar", foo_bar, METH_VARARGS},
{NULL, NULL}
};
/* Here's the initialization function. We don't need to do anything
for our own needs, but Python needs that method table. */
void initfoo()
{
(void) Py_InitModule("foo", FooMethods);
}
/* Finally, let's do something ... involved ... as an example function. */
static PyObject *foo_bar(PyObject *self, PyObject *args)
{
char *string;
int len;
if (!PyArg_ParseTuple(args, "s", &string))
return NULL;
len = strlen(string);
return Py_BuildValue("i", len);
}
C定义文件:foo.def
EXPORTS
initfoo
编译生成foo.dll
cl -c foo.c;
link foo.obj /dll /def:foo.def /OUT:foo.dll
将foo.dll 改名为 foo.pyd
在PYTHON中调用:
import foo
dir(foo)
…
即可以看到结果:
>>> import foo
>>> dir(foo)
['__doc__', '__file__', '__name__', 'bar']
>>> ^Z
3 C调用由python生成的dll
写一个C程序,该程序存放调用python的函数接口。然后将该C程序和python程序一起做成DLL即可。
主要参考
Anjuta: C++ IDE for Ubuntu
Linux下C/C++工具推荐Anjuta
vi/vim, gedit 和emacs is simple
KDeveloper is based on KDE
Eclipse, 基于Java的IDE, 慢,耗内存
NetBeans , 基于Java
基于GTK/Glade的Anjuta集成开发环境(IDE)不错,体积小,速度快,有自动代码补全和提示功能. I feel even for python IDE, anjuta can beat eric-python!
1. Install anjuta directly by menu->Applications->add/remove->programming
2. 安装C/C++开发文档
在编程的过程中有时会记不得某个函数的用法,通常这时查man手册是比较快的,所以把这个manpages-dev软件包安装上。想要看某个函数的用法就man它。
执行安装命令: sudo apt-get install manpages-dev
manpage的索引由mandb命令管理,有时在安装了新的manpage文件后,可能需要更新一下索引才能看到man -k 和man -f这些函数。
执行命令:mandb -c
然后,就可以查看这些文档了。比如,fopen的:
man fopen
3. 写个Hello World 的C++程序
在Anjuta中新建Project。出现“应用程序向导”,点“前进”;工程类型选“C++”中的“Generic C++”,之后点“前进”;“前进”;工程选项(Project Options)中,全选“否”,再点“前进”,应用即可。点左侧“工程”按钮,点工程名“foobar-cpp”,双击“main.cc”打开它,可以看到,main() 函数已预先写好了。按下“Shift+F11”编译,再按“F3”运行(这两个快捷键对应菜单在“Build”菜单下。),Anjuta的更多功能等待发掘,点击“设置”》“Plugins”...
References:
[1] http://anjuta.org/apt
[2] http://forum.ubuntu.org.cn/viewtopic.php?t=79137
vi/vim, gedit 和emacs is simple
KDeveloper is based on KDE
Eclipse, 基于Java的IDE, 慢,耗内存
NetBeans , 基于Java
基于GTK/Glade的Anjuta集成开发环境(IDE)不错,体积小,速度快,有自动代码补全和提示功能. I feel even for python IDE, anjuta can beat eric-python!
1. Install anjuta directly by menu->Applications->add/remove->programming
2. 安装C/C++开发文档
在编程的过程中有时会记不得某个函数的用法,通常这时查man手册是比较快的,所以把这个manpages-dev软件包安装上。想要看某个函数的用法就man它。
执行安装命令: sudo apt-get install manpages-dev
manpage的索引由mandb命令管理,有时在安装了新的manpage文件后,可能需要更新一下索引才能看到man -k 和man -f这些函数。
执行命令:mandb -c
然后,就可以查看这些文档了。比如,fopen的:
man fopen
3. 写个Hello World 的C++程序
在Anjuta中新建Project。出现“应用程序向导”,点“前进”;工程类型选“C++”中的“Generic C++”,之后点“前进”;“前进”;工程选项(Project Options)中,全选“否”,再点“前进”,应用即可。点左侧“工程”按钮,点工程名“foobar-cpp”,双击“main.cc”打开它,可以看到,main() 函数已预先写好了。按下“Shift+F11”编译,再按“F3”运行(这两个快捷键对应菜单在“Build”菜单下。),Anjuta的更多功能等待发掘,点击“设置”》“Plugins”...
References:
[1] http://anjuta.org/apt
[2] http://forum.ubuntu.org.cn/viewtopic.php?t=79137
2009/03/08
ctypes, pyrex and Boost
ctypes 是为方便python程序调用C dll程序的接口而规范数据类型。
-ctypes是一个Python模块,
-可在Python中创建和操作C语言的数据类型
-可在动态链接库中传递参数到C的函数中去
Pyrex 是将Python脚本转化为可编译的C代码,以便高效执行和被C程序调用。
- 它有多出的语法(除与python兼容外)
- 它需要 pyrexc test.pyx 生成 C代码 test.c
- 然后编译成 test.so 或 test.dll
Boost_python是方便写python程序调用C dll.
相对来说 ctypes使用较方便! 使用pyrex,如果需要在Python代码访问C代码的Struct和Union,比较麻烦。
cytpes tutorial
Pyrex - a Language for Writing Python Extension Modules
pyrex一例
1,先生成简单的
//test.h
int tadd(int a, int b);
//test.c
#include "test.h"
int tadd(int a, int b) { return a+b; };
gcc -c test.c #生成test.o
ar -rsv libtest.a test.o #生成了 libtest.a 静态库
2 测试lib是否可用
// ttest.c
#include
#include "test.h"
void main(int argc, void * argv[])
{ int c=1; c = tadd(1, 4); printf("c = %d \r\n", c); }
gcc ttest.c -ltest -L. #生成了a.out
./a.out #结果是: c = 5
证明我们的lib库是可以正常工作的
3,写一个python的模块td.pyx,调用它libtest里的tadd()函数
#td.pyx
cdef extern from "test.h":
int tadd(int i, int j)
def tdadd(int i, int j):
cdef int c
c=tadd(i, j) #在这行调用c=tadd(i, j)
return c
编译:
pyrexc td.pyx #生成 td.c
gcc -c -fPIC -I/usr/include/python2.4/ td.c #生成td.o
gcc -shared td.o -ltest -L. -o td.so #生成了td.so。这个就是python可以用的模块so
安装 pyrex,略。
测试:
import td
dir(td)
['__builtins__', '__doc__', '__file__', '__name__', 'tdadd']
td.tdadd(1,2)
3
OK。
-ctypes是一个Python模块,
-可在Python中创建和操作C语言的数据类型
-可在动态链接库中传递参数到C的函数中去
Pyrex 是将Python脚本转化为可编译的C代码,以便高效执行和被C程序调用。
- 它有多出的语法(除与python兼容外)
- 它需要 pyrexc test.pyx 生成 C代码 test.c
- 然后编译成 test.so 或 test.dll
Boost_python是方便写python程序调用C dll.
相对来说 ctypes使用较方便! 使用pyrex,如果需要在Python代码访问C代码的Struct和Union,比较麻烦。
cytpes tutorial
Pyrex - a Language for Writing Python Extension Modules
pyrex一例
1,先生成简单的
//test.h
int tadd(int a, int b);
//test.c
#include "test.h"
int tadd(int a, int b) { return a+b; };
gcc -c test.c #生成test.o
ar -rsv libtest.a test.o #生成了 libtest.a 静态库
2 测试lib是否可用
// ttest.c
#include
#include "test.h"
void main(int argc, void * argv[])
{ int c=1; c = tadd(1, 4); printf("c = %d \r\n", c); }
gcc ttest.c -ltest -L. #生成了a.out
./a.out #结果是: c = 5
证明我们的lib库是可以正常工作的
3,写一个python的模块td.pyx,调用它libtest里的tadd()函数
#td.pyx
cdef extern from "test.h":
int tadd(int i, int j)
def tdadd(int i, int j):
cdef int c
c=tadd(i, j) #在这行调用c=tadd(i, j)
return c
编译:
pyrexc td.pyx #生成 td.c
gcc -c -fPIC -I/usr/include/python2.4/ td.c #生成td.o
gcc -shared td.o -ltest -L. -o td.so #生成了td.so。这个就是python可以用的模块so
安装 pyrex,略。
测试:
import td
dir(td)
['__builtins__', '__doc__', '__file__', '__name__', 'tdadd']
td.tdadd(1,2)
3
OK。
订阅:
博文 (Atom)