Accessing the content of a variable array with ctypes

2024/11/10 13:44:02

I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C .

int read_file(const char *file,int *n_,int *m_,float **data_) {...}

The functions mallocs an 2d array, called data, of the appropriate size, here n and m, and copies the values to the referenced ones. See following snippet:

*data_ = data;
*n_ = n;
*m_ = m;

I access this function with the following python code:

p_data=POINTER(c_float)
n=c_int(0)
m=c_int(0)
filename='datasets/usps'
read_file(filename,byref(n),byref(m),byref(p_data))

Afterwards I try to acces p_data using contents, but I get only a single float value.

p_data.contents
c_float(-1.0)

My question is: How can I access data in python?

What do you recommended? Please don't hesitate to point out if I left something unclear!

Answer

might be simpler to do the whole thing in python with the struct library. but if you're sold on ctypes (and I don't blame you, it's pretty cool):

#include <malloc.h>
void floatarr(int* n, float** f)
{int i;float* f2 = malloc(sizeof(float)*10);n[0] = 10;for (i=0;i<10;i++){ f2[i] = (i+1)/2.0; }f[0] = f2;
}

and then in python:

from ctypes import *fd = cdll.LoadLibrary('float.dll')
fd.floatarr.argtypes = [POINTER(c_int),POINTER(POINTER(c_float))]fpp = POINTER(c_float)()
ip = c_int(0)
fd.floatarr(pointer(ip),pointer(fpp))
print ip
print fpp[0]
print fpp[1]

the trick is that capitals POINTER makes a type and lowercase pointer makes a pointer to existing storage. you can use byref instead of pointer, they claim it's faster. I like pointer better because it's clearer what's happening.

https://en.xdnf.cn/q/72354.html

Related Q&A

What is the stack in Python?

What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What …

Pandas: Resample dataframe column, get discrete feature that corresponds to max value

Sample data:import pandas as pd import numpy as np import datetimedata = {value: [1,2,4,3], names: [joe, bob, joe, bob]} start, end = datetime.datetime(2015, 1, 1), datetime.datetime(2015, 1, 4) test =…

How to filter string in multiple conditions python pandas

I have following dataframeimport pandas as pd data=[5Star,FiveStar,five star,fiv estar] data = pd.DataFrame(data,columns=["columnName"])When I try to filter with one condition it works fine.d…

Is there a way to use a dataclass, with fields with defaults, with __slots__

I would like to put __slots__ on a dataclass with fields with defaults. When I try do that, I get this error: >>> @dataclass ... class C: ... __slots__ = (x, y, ) ... x: int ... y:…

Read remote file using python subprocess and ssh?

How can I read data from a big remote file using subprocess and ssh?

Django - get_queryset() missing 1 required positional argument: request

I was trying to make an API using REST Framework for uploading a file to the server and my codes are below.If you have any other easy method to do the same please post your code.models.pyfrom django.db…

Storing elements of one list, in another list - by reference - in Python?

I just thought Id jot this down now that Ive seen it - it would be nice to get a confirmation on this behavior; I did see How do I pass a variable by reference?, but Im not sure how to interpret it in…

Joining Two Different Dataframes on Timestamp

Say I have two dataframes:df1: df2: +-------------------+----+ +-------------------+-----+ | Timestamp |data| | Timestamp |stuff| +-------------------+---…

Find if the array contain a 2 next to a 2

I am stuck on this problemGiven an array of ints, return True if the array contains a 2 next to a 2 somewhere.has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → FalseI know the b…

AttributeError: xml.etree.ElementTree.Element object has no attribute encode

Im trying to make a desktop notifier, and for that Im scraping news from a site. When I run the program, I get the following error.news[child.tag] = child.encode(utf8) AttributeError: xml.etree.Element…