简体   繁体   中英

Return an array of floats in C++ to Python

I'm fairly sure I'm not looking in the right places, because information on this topic has been remarkably hard to come by.

I have a small function in C++ that Python will invoke and that create a small array of floats and return them to Python.

First, it appears that you cannot use Py_BuildValue() to return an array of arbitrary size in C++ as a list in Python (it is unclear to me why this should be). An old but still-relevant post here suggests instantiating a PyList object, populating it with elements from the array, and then returning that instead.

Which is an acceptable solution. However, my numbers are C++ style floats. While the Python library provides ample conversion operations (C string -> Python string, C double -> Python float, etc), I can't find a means to simply convert a C++ float to a Python float. I know Python floats are equivalent to C/C++ doubles, so I suppose I could cast the floats to doubles and then to a PyObject via PyFloat_FromDouble() but I feel there must exist a more direct way of doing this.

Because this is an exceedingly short function, and largely a proof of concept, I did not feel it should be necessary to take the time to learn SWIG or Boost Python or somesuch; I'd like to do this with the built-in Python/C++ API. Any suggestions would be greatly appreciated!

Since a Python float is essentially a C double , the conversion has to happen at some point or other. Quoting the reference :

Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.

So convert to double (possibly simply by passing the value to a function which accepts double ) and you are set.

As the text also indicates, floating point values in python are objects, which come with quite a bit of overhead. PyFloat_FromDouble will take care of getting that right. So going through that function is the right thing to do. The same holds for list creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM