我几天前开始学习C ++。
我想编译这个示例程序,以便在C ++中嵌入Python。
C ++程序是:
#include <Python.h>
#include <iostream>
#define pi 3.141592653589793
using namespace std;
int main () {
//Inicio el interprete Python e imprimo informacion relevante
Py_Initialize();
PyObject *FileScript;
FileScript = PyFile_FromString("script.py","r");
PyRun_SimpleFile(PyFile_AsFile(FileScript),"r");
PyObject *retorno, *modulo, *clase, *metodo, *argumentos, *objeto;
int *resultado;
modulo = PyImport_ImportModule("script");
clase = PyObject_GetAttrString(modulo, "Numeros");
argumentos = Py_BuildValue("ii",5,11);
objeto = PyEval_CallObject(clase, argumentos);
metodo = PyObject_GetAttrString(objeto, "suma");
argumentos = Py_BuildValue("()");
retorno = PyEval_CallObject(metodo,argumentos);
PyArg_Parse(retorno, "i", &resultado);
cout<<"Result is: "<<int(resultado)<<endl;
Py_Finalize();
char terminar;
cin>>terminar;
return 1;
}
和python脚本“script.py”是:
class Numeros:
def __init__(self, num1, num2):
self.num1=num1
self.num2=num2
def suma(self):
print self.num1, self.num2
return self.num1+self.num2
我正在使用安装了G ++的Ubuntu。我输入这个来编译:
g++ -I/usr/include/python2.7 -lpython2.7 main.cpp -o main
但是我收到了这个错误:
main.cpp:27:42: error: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
cout<<"Result is: "<<int(resultado)<<endl;
我该如何解决?非常坦克!
答案 0 :(得分:1)
指针的大小可能大于int的大小并且取决于内存模型。
int iSomeValue = 0;
std::cout << "size of int = " << sizeof(iSomeValue)<< " | size of pointer = " << sizeof(&iSomeValue);
对于Visual Studio 2013,Win32输出为:
int = 4的大小指针大小= 4
对于Visual Studio 2013 x64输出是:
int = 4的大小指针大小= 8