简体   繁体   中英

C++ error: cast from ‘int*’ to ‘int’ loses precision

I started learning C++ a few days ago.

I want to compile this example program in order to embed Python in C ++.

The C++ program is:

#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;
}

and python script "script.py" is:

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

I´m using Ubuntu with G++ installed. I type this to compile:

g++ -I/usr/include/python2.7 -lpython2.7 main.cpp -o main

But I get this error:

main.cpp:27:42: error: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
  cout<<"Result is: "<<int(resultado)<<endl;

How can I solve it? Tank you very much!

Size of pointer may be greater than size of int and depends of memory model.

int iSomeValue = 0;
std::cout << "size of int = " << sizeof(iSomeValue)<< " | size of pointer = " << sizeof(&iSomeValue);

For Visual Studio 2013 Win32 output is:

size of int = 4 | size of pointer = 4

For Visual Studio 2013 x64 output is:

size of int = 4 | size of pointer = 8

For a 64bit machine, it's tricky to cast an int pointer(hex format) to int value or char pointer to int value because each block of memory for an int variable is 32 bit and for char it's 8 bit. For example:

1. char SomeString[] = "Hello!";
2. char *pString = SomeString;
3. cout << "pString = " << pString << endl;
4. char *pLocation3 = &SomeString[3];
5. cout << "pLocation3 = " << (int)pLocation3 << endl;

You will get an error: cast from 'char*' to 'int' loses precision [-fpermissive]

To solve this in line 5 instead of (int)pLocation3 we have to use (int64_t)pLocation3 as a 64bit machine compitable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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