以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; }