2017-04-09 34 views
0

我需要你的幫助!如何從C++調用另一個文件中定義的python函數?

我如何可以調用C++基於以下的.py源蟒蛇功能:

DefineEasyCalls.py

def myfun(): 
    return 100 

Testfile.py

from DefineEasyCalls import * 
fun = myfun() 

我想用Testfile.py作爲我的C++程序中的Inputfile。在那裏,我想打電話給myfun()並用它做些事情。你有什麼想法如何做到這一點?也許我用C++導入這兩個文件,並檢查Testfile.py中是否有一個名爲myfun的方法,並且從testfile.py文件中調用相應的函數,但是如果Testfile.py中有myfun的函數輸入會怎麼樣?在這種情況下,這種策略對我來說不起作用。

如果我在Testfile.py中直接定義myfun(Testfile.py中的代碼= DefineEasyCalls.py),那麼事情就會奏效。但是我想使用Testfile.py作爲輸入文件而不是DefineEasyCalls.py!此外,我還想給TestFile.py中的myfun提供一些輸入參數,這些輸入參數我也想在後面的C++中使用。有人知道如何做到這一點?

這裏是我的C++代碼:

#include <Python.h> 
#include <stdlib.h> 
#include <iostream> 
using namespace std; 

int callmyfun(); 

int main() 
{ 
    int a = callmyfun(); 
    int b = 1; 
    cout << a+b << endl; 
    cin.get(); 
    return 0; 
} 


int callmyfun() 
{ 
PyObject *pName, *pModule, *pDict, *pFunc; 
PyObject *pValue; 

Py_Initialize(); 

PyObject* sysPath = PySys_GetObject("path"); 
PyList_Append(sysPath, PyBytes_FromString("C:/ .. path .../x64/Release")); 

// Load the module 
pName = PyUnicode_DecodeFSDefault("Testfile"); 
pModule = PyImport_Import(pName); 
Py_DECREF(pName); 

cout << pName << endl; 

if (pModule != NULL) 
{ 
    cout << "module found\n"; 
    pDict = PyModule_GetDict(pModule); 
    pFunc = PyObject_GetAttrString(pModule, "myfun"); 

    if (pFunc != NULL) { 
     pValue = PyObject_CallObject(pFunc, NULL); 
     printf("Result of call: %ld\n", PyLong_AsLong(pValue)); 
     Py_DECREF(pValue); 
     long long L = PyLong_AsLongLong(pValue); 
     return L; 
    } 
    else { 
     std::cout << "Couldn't find func\n"; 
     return 0; 
    } 
} 
else 
{ 
    cout << "module not found!\n"; 
    return 0; 
} 

    Py_Finalize(); 
} 

我用MSVC2015和Python 3.6。感謝您的幫助!

+0

此外,我怎麼能從C++的Testfile.py中調用例如myfun(10)? – stevula

回答

0

找到了適合我的解決方案! :)

  • 創建一個C++類,其中包含期望的功能
  • 創建Python擴展模塊(我用痛飲)
  • 呼叫經由Python擴展模塊中Testfile.py
功能

另一種方法可能會將DefineEasyCalls.py放入模塊目錄加載路徑中,並將其導入到Testfile.py中,但這對我來說並不適用。在這裏,我找不到c api搜索python模塊(如numpy)的路徑。也許有人知道如何以這種方式進行思考?

相關問題