0

I want to pass the address of a numpy array buffer to c function, My C function looks like:

void print_float_buff(void *buff)
{
    float *b = (float *)buff;
    printf("Float Data: %f, %f, %f,\n", b[0], b[1], b[2]);
}

In python my code is:

import numpy as np
fun=ctypes.CDLL("./mylib.so")
l = np.array([10., 12.6, 13.5], dtype = 'float')
address, flag = l.__array_interface__['data']
fun.print_float_buff(ctypes.c_void_p(address))

A am getting completely different data in my c function. Address doesn't seem good. How can I pass correct address to my C function? Thanks.

2 Answers 2

1

If you specify .argtypes correctly, ctypes will tell you the type is wrong. Below requires a one-dimensional array compatible with c_float:

test.c

#include <stdio.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API void print_float_buff(float *buff, size_t size)
{
    for(size_t i = 0; i < size; ++i)
        printf("buff[%zu] = %f\n",i,buff[i]);
}

test.py

from ctypes import *
import numpy as np

dll = CDLL('./test')
dll.print_float_buff.argtypes = np.ctypeslib.ndpointer(c_float,ndim=1),c_size_t
dll.print_float_buff.restype = None

a = np.array([10., 12.6, 13.5])
dll.print_float_buff(a,len(a))

Output:

Traceback (most recent call last):
  File "C:\test.py", line 9, in <module>
    dll.print_float_buff(a,len(a))
ctypes.ArgumentError: argument 1: <class 'TypeError'>: array must have data type float32

Changing the array as suggested:

a = np.array([10., 12.6, 13.5],dtypes='float32')

Output:

buff[0] = 10.000000
buff[1] = 12.600000
buff[2] = 13.500000
Sign up to request clarification or add additional context in comments.

Comments

0

I found the issue. In c, float size is four bytes while in python float size is 8 bytes. If I allocate array like this:

l = np.array([10., 12.6, 13.5], dtype = 'float32')

it works fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.