user2349460
user2349460

Reputation: 35

Segmentation fault in python while using ctypes

I am trying to read some registers in hardware (FPGA) using Python. I already have a C code to read the registers and it works fine. I want to use them in python using ctypes.

rdaxi.c

#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define NF10_IOCTL_CMD_READ_STAT (SIOCDEVPRIVATE+0)
#define NF10_IOCTL_CMD_WRITE_REG (SIOCDEVPRIVATE+1)
#define NF10_IOCTL_CMD_READ_REG (SIOCDEVPRIVATE+2)  

int main(int argc, char* argv[]){
    int f;
    uint64_t v;
    uint64_t addr;

    if(argc < 2){
        printf("usage: rdaxi reg_addr(in hex)\n\n");
        return 0;
    }
    else{
        sscanf(argv[1], "%llx", &addr);
    }

    //----------------------------------------------------
    //-- open nf10 file descriptor
    //----------------------------------------------------
    f = open("/dev/nf10", O_RDWR);
    if(f < 0){
        perror("/dev/nf10");
        return 0;
    }

    printf("\n");

    v = addr;
    if(ioctl(f, NF10_IOCTL_CMD_READ_REG, &v) < 0){
        perror("nf10 ioctl failed");
        return 0;
    }
    // upper 32bits contain the address and are masked away here
    // lower 32bits contain the data
    v &= 0xffffffff;

    printf("AXI reg 0x%llx=0x%llx\n", addr, v);

    printf("\n");

    close(f);

    return 0;
}

After comilation and getting the executable, I just do the following to get my result

./rdaxi 0x5a000008
AXI reg 0x5a000008 = 2

I want to do the same thing using Python.I came to know that I have to use Ctypes. Then I created shared library (.so) for my c file.The following is the python code i wrote. I am a beginner in python, so pardon me for my errors. I get a segmentation fault. How can I solve this and read the registers.

rdaxi.py

#!/usr/bin/env python

# For creating shared library
# gcc -c -Wall -fPIC rdaxi.c
# gcc -shared -o librdaxi.so rdaxi.o



import os
import sys
from ctypes import *
print "opening device descriptor"
nf = os.open( "/dev/nf10", os.O_RDWR )
print "loading the .so file"
librdaxi=cdll.LoadLibrary('/root/Desktop/apps/librdaxi.so')
librdaxi.main(nf,0x5b000008)

For more information about my application. Please see below. reading registers in hw using python

thanks

Upvotes: 3

Views: 1956

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

main() takes two parameters, argc and argv, but you are passing it a single parameter which is your address.

Here's an example of how you might call it:

librdaxi.main.argtypes = [c_int,POINTER(c_char_p)]
argv=(c_char_p*2)()
argv[0]='rdaxi'
argv[1]='0x5a000008'
librdaxi.main(2,argv)

Upvotes: 2

Related Questions