[C++-sig] interfacing headle binary file library, raw pointer and buffer
Nat Goodspeed
nat at lindenlab.com
Sun Jun 20 15:54:37 CEST 2010
heroxbd at gmail.com wrote:
> I am trying to interface a binary file library using py++.
>
> There is a function in the library like
>
> int read(void* buffer, size_t len)
>
> which is hard to wrap. It read a piece (size len) of the file, and store
> it in buffer, and then return the buffer length (most likely equal to len).
You want to write a C++ wrapper function something like this:
std::string wrapped_read(size_t len)
{
// manually allocate buffer of size 'len',
// e.g. by using std::vector<char>
int bytes_read = read(buffer, len);
return std::string(buffer, bytes_read);
// If you literally used 'new' or 'malloc' to obtain your 'buffer',
// rather than a type such as std::vector which will release
// its dynamic memory automatically, of course the 'return'
// above would leak 'buffer'. In that case you'd have to declare
// std::string result(buffer, bytes_read);
// ...manually release 'buffer'...
// return result;
}
Then wrap the C++ function wrapped_read() as the Python function "read".
Boost.Python is very happy passing std::string in either direction.
Trying to directly use char* or void* buffers is perilous and will, as
you remark, make the consumers of your library unhappy.
More information about the Cplusplus-sig
mailing list