Python Forum
Help with ctypes and "c_int*"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with ctypes and "c_int*"
#1
I am python beginner and I am trying to run a simple python program that call a c function using ctypes
on a linux Ubuntu PC.

It is based on web examples, but I have not the full source code of "test_funtionslib_using_wrapper.py".

Besides I prefer not to use additional python packets, as numpy or others, and being able to run it on initial python installation for Ubuntu.

funtionslib.c
#include <stdio.h>

void c_square(int n, double *array_in, double *array_out)
{
  int i;

  for (i=0; i<n; i++)
  {
    array_out[i] = array_in[i] * array_in[i];
  }
}
testlibwrapper.py
from ctypes import *
import sys

clib_path = "./functionslib_linux.so"
try:
  c_functions_lib = CDLL(clib_path)
except:
  print("No se ha podido abrir la libreria " + str(clib_path))

def do_square_using_c(list_in):
  n = len(list_in)
  c_array_in = (c_double* n)(*list_in)
  c_array_out = (c_double* n)()

  function_c_square = c_functions_lib.c_square
  function_c_square.restype = None
  function_c_square(c_int(n), c_array_in, c_array_out)

  return c_array_out[:]
test_funtionslib_using_wrapper.py
from testlibwrapper import do_square_using_c

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_list = do_square_using_c(*my_list)
compile.sh (optional script to compile C linux library)
gcc -shared -Wl,-soname,testlib -o functionslib_linux.so -fPIC functionslib.c
run_python.sh (optional script to run python)
  #!/bin/bash
  python testlibwrapper.py



When I run, I get the error:

Traceback (most recent call last):
File "test_funcionslib_using_wrapper.py", line 7, in <module>
squared_list = do_square_using_c(*my_list)
TypeError: do_square_using_c() takes exactly 1 argument (10 given)


How can I fix this error without using numpy?

The original source of "test_funtionslib_using_wrapper.py" on the web is:

from testlibwrapper import do_square_using_c
import numpy as np

#Previous declarations or initializations are not detailed on the web
# (. . .)

my_list = np.arange(1000)
squared_list = do_square_using_c(*my_list)
Reply
#2
try removing the * from squared_list = do_square_using_c(*my_list)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020