【发布时间】:2018-05-30 01:40:50
【问题描述】:
当我将一些 python 代码嵌入到我的 C++ 程序中并尝试导入 python 模块并获取指向它的指针时,我有两个选择:
将空指针作为参数传递:
void importPyModule(PyObject * modPtr, const char *modName){
modPtr = PyImport_ImportModule(modName);
if(modPtr == nullptr){
std::cout << "python module: " << modName << " import failed\npython message: ";
PyErr_Print();
std::exit(1);
}
}
或者返回一个指针:
PyObject *importPyModule(const char *modName){
PyObject *modPtr = PyImport_ImportModule(modName);
if(modPtr == nullptr){
std::cout << "python module: " << modName << " import failed\npython message: ";
PyErr_Print();
std::exit(1);
}
}
为了完整起见,这是我调用函数的地方:
#include "Python.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
int main(){
initPython(); // initialize the interpreter and set appropriate paths
PyObject *aws_tools, *boto, *imp, *sdb;
// Option 1: return pointer
aws_tools = importPyModule("aws_tools");
// Or option 2: pass a pointer
importPyModule(aws_tools, "aws_tools");
/* Some other code */
return 0;
}
当我将指针作为参数传递时,我得到一个指向:
<unknown at [some address]>
但是当我将指针从函数返回值时,我得到:
<module at [some address]>
指向模块的指针会正常工作,而指向未知的指针会导致程序崩溃。
我的问题是:有没有比使用指针更好的方法来完成这项工作?
是什么导致了这里的行为差异?
我正在使用带有 c++11 标准和 python2.6 的 g++
【问题讨论】:
-
对于选项 1,您需要通过引用传递指针。否则,您将分配给不影响给定指针的副本。
-
天哪,我觉得自己很笨
标签: python c++ pointers parameter-passing return-value