简体   繁体   English

在C ++应用程序中包含第三方python模块

[英]Including 3rd party python module in c++ application

I am trying to build an application to parse netCDF4 files in c++. 我正在尝试构建一个应用程序来解析c ++中的netCDF4文件。

What I have done: 我做了什么:

  • Succeeded in parsing the files in python scripts. 在python脚本中解析文件成功。

What I need help with: 我需要什么帮助:

  • Including my python script as a module. 包括我的python脚本作为模块。 When I run my C++ program it complains that it can't access numPy. 当我运行C ++程序时,它抱怨它无法访问numPy。

What I Know: 我知道的:

  • I fixed the same issue with the netCDF4 by copying the netCDF4.pyd file where my c++ executable was located, but cannot find the numPy. 通过复制c ++可执行文件所在的netCDF4.pyd文件,但找不到numPy,我修复了netCDF4的相同问题。 equivalent. 当量。

Thanks for any suggestions. 感谢您的任何建议。

Welcome to the community! 欢迎来到社区! I hope I understand the question correctly - is it importing a python module into c++? 我希望我正确理解了这个问题-将python模块导入c ++吗? If that is so, try the following tutorial: Embedding Python in C/C++: Part I . 如果是这样,请尝试以下教程: 在C / C ++中嵌入Python:第一部分

Basically, to paraphrase, DON'T use code conversion or translation - it is unnecessairly complex. 基本上,换句话说,不要使用代码转换或翻译-它不必要地很复杂。 Just make the python code communicate with the C code as follows. 只需使python代码与C代码进行通信即可,如下所示。 Kudos to website above for the code, comments by me. 感谢上面的代码,我的评论。

#include <Python.h> //get the scripts to interact

int main(int argc, char *argv[])
 {
PyObject *pName, *pModule, *pDict, *pFunc, *pValue; //Arguments that are required.

if (argc < 3) 
{
    printf("Usage: exe_name python_source function_name\n");
    return 1;
}

// Allow your program to understand python
Py_Initialize();

// Initialize Name
pName = PyString_FromString(argv[1]);

// Import the module from python
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// same situiation as above 
pFunc = PyDict_GetItemString(pDict, argv[2]);

if (PyCallable_Check(pFunc)) 
{
    PyObject_CallObject(pFunc, NULL);
} else 
{
    PyErr_Print();
}

// Tidy Everything Up.
Py_DECREF(pModule);
Py_DECREF(pName);

// End interpreter
Py_Finalize();

return 0;
}

I suggest you read the above tutorial, though. 我建议您阅读上面的教程。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM