Python 嵌入C++/C等

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

    TCHAR Buffer[BUFSIZ];

    DWORD dwRet = GetCurrentDirectory(BUFSIZ,Buffer);

     WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, (Buffer), -1, ch, sizeof(ch), NULL, NULL );

//这个和下面的三句是一样的效果
//啊``` 神那, tchar, cstring char* 还是搞得云里雾里的, 得再看下...
CString strPath; 
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(); 
int len = strlen(ch);
string fileName = "\\test.py";
for( int i = 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("exit 1"); system("pause"); return 1; } 
FILE *f = PyFile_AsFile(pyfile); 
if(f==NULL) 
        { printf("exit 2"); system("pause"); return 1; } 
PyRun_AnyFileEx(f,"test.py",0); 
 另外一种是直接插入语句执行
string pythonCode = "print('Hello world,I am python!')"; 
PyRun_SimpleString( pythonCode );
 
代码:
// pythonPluginTest.cpp : 
// 

#pragma once

#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>
using namespace std; 

int _tmain(int argc, _TCHAR* argv[])
{
    Py_Initialize();//启动python解释器
    //////////////////////// 

        CString strPath; 

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

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

    strPath.ReleaseBuffer(); 

    string tmpStr;
    cout << ch << endl; 

    int len = strlen(ch); 

    string fileName = "\\test.py"; 

    for( int i = 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("exit 1");
        system("pause");
        return 1;
    } 
    FILE *f = PyFile_AsFile(pyfile); 
    if(f==NULL)
    {
        printf("exit 2");
        system("pause");
        return 1; 

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

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

    /////////////////////// 

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

    return 0; 

} 

posted on 2010-08-20 21:50  amojry  阅读(2352)  评论(0编辑  收藏  举报