您的位置:首页 > 编程语言 > C语言/C++

Python 嵌入C++/C等

2010-08-20 21:50 239 查看
以python2.6为例;
1.用python的源代码,打开编译出python26.dll,python26.lib,python26_d.lib和python26_d.dll.加入lib目录中,和放到system32文件夹内.
2.就可以进行下面的代码了.
附加的一点:获取当前程序的运行目录:


TCHARBuffer[BUFSIZ];
DWORDdwRet=GetCurrentDirectory(BUFSIZ,Buffer);
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,(Buffer),-1,ch,sizeof(ch),NULL,NULL);
//这个和下面的三句是一样的效果
//啊```神那,tchar,cstringchar*还是搞得云里雾里的,得再看下...
CStringstrPath;
GetCurrentDirectory(MAX_PATH,strPath.GetBuffer(MAX_PATH));
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,(strPath.GetBuffer(strPath.GetLength()+1)),
-1,ch,sizeof(ch),NULL,NULL);//将wchar_t*转换成char*....可以参考上篇日志关于UNICODE和ASCI
strPath.ReleaseBuffer();
intlen=strlen(ch);
stringfileName="\\test.py";
for(inti=0;i<fileName.length();i++)
ch[len++]=fileName[i];
ch[len]='\0';
定位到你要找的那个.py的文件路径.
主要下面的pyobject的初始的路径和VS的默认处理路径debug文件夹不一样.所以这么做..
也是自寻烦恼吧..
3.python的两种嵌入方法,一种是直接调用已经有的py文件.

PyObject*pyfile=PyFile_FromString(ch,"r");

if(pyfile==NULL)
{printf("exit1");system("pause");return1;}

FILE*f=PyFile_AsFile(pyfile);

if(f==NULL)
{printf("exit2");system("pause");return1;}

PyRun_AnyFileEx(f,"test.py",0);
另外一种是直接插入语句执行
stringpythonCode="print('Helloworld,Iampython!')";
PyRun_SimpleString(pythonCode);
代码:

//pythonPluginTest.cpp:
//
#pragmaonce

#include"targetver.h"

#include<stdio.h>
#include<tchar.h>

#define_AFXDLL
#include"stdafx.h"
#include<stdio.h>
#include<string>
#include<iostream>
#include<fstream>
#include<Python.h>
#include<cstring>
#include<afx.h>
usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])
{
Py_Initialize();//启动python解释器
////////////////////////CStringstrPath;

GetCurrentDirectory(MAX_PATH,strPath.GetBuffer(MAX_PATH));

charch[BUFSIZ];
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,(strPath.GetBuffer(strPath.GetLength()+1)),-1,ch,sizeof(ch),NULL,NULL);
;

strPath.ReleaseBuffer();

stringtmpStr;
cout<<ch<<endl;

intlen=strlen(ch);

stringfileName="\\test.py";

for(inti=0;i<fileName.length();i++)
ch[len++]=fileName[i];

ch[len]='\0';

cout<<ch<<endl;
//直接调用已有的python的py程序
PyObject*pyfile=PyFile_FromString(ch,"r");
if(pyfile==NULL)
{
printf("exit1");
system("pause");
return1;
}
FILE*f=PyFile_AsFile(pyfile);
if(f==NULL)
{
printf("exit2");
system("pause");
return1;

}
PyRun_AnyFileEx(f,"test.py",0);

//直接运行指令,指令都是字符串,注意3.1.1版的python必须加上小括号
PyRun_SimpleString("print('Helloworld,Iampython!')");

///////////////////////Py_Finalize();//关闭python解释器
system("pause");

return0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐
章节导航