• Uncategorized

About python : getting-None-instead-of-a-integer-value-closed

Question Detail

I am calling c++ code from python and I was wondering why I am not getting an integer value back from my function which returns an int. I keep getting None in python.

This is my c++ code:

#include <wiringPi.h>
#include <wiringPiI2C.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;

class Ultrasonic {
        int returnDistance() {
            int fd;
            fd=wiringPiI2CSetup(0x70) ;//i2c addres
            //unsigned char arr[2]={00,0x51};//register port and command
            int data;

            wiringPiI2CWriteReg8(fd,00, 81);
            data = wiringPiI2CReadReg8(fd,3);
            cout << "datatype of data is: " << typeid(data).name() << endl;
            return data;

int main(){

    Ultrasonic ultrasonic;


    return 0;


extern "C" {
    Ultrasonic* Ultrasonic_new(){ return new Ultrasonic(); }
    int Ultrasonic_returnDistance(Ultrasonic* ultrasonic){ return ultrasonic -> returnDistance(); }

This is my python code:

# import the modules
from base64 import encode
from ctypes import cdll
import socket, time

lib3 = cdll.LoadLibrary('./libUltra.so')

class Ultrasonic(object):

     # constructor
    def __init__(self):
        # attribute
        self.obj = lib3.Ultrasonic_new()
    def returnDistance(self):

ultra = Ultrasonic()


This is the output I get:

<class ‘main.Ultrasonic’>

datatype of data is: i (which stands for integer)

<type ‘NoneType’> (should be integer)

If it matters, I am using these commands:

g++ -c -fPIC ultra.cpp -o ultra.o -lwiringPi

g++ -shared -Wl,-soname,libUltra.so -o libUltra.so ultra.o -lwiringPi

Question Answer

Fix your Python returnDistance function to return the value:

    def returnDistance(self):
        return lib3.Ultrasonic_returnDistance(self.obj)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.