2017-04-09 61 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)的路径。也许有人知道如何以这种方式进行思考?

相关问题