[C++-sig] RE: ÆC++-sigÅ How to export arrays from C(++) to python using boost
Kirsebom Nikolai
nikolai.kirsebom at siemens.no
Mon Feb 9 15:16:06 CET 2004
> -----Original Message-----
> From: Shukla, Nitin (Export) [mailto:nitin.shukla at pw.utc.com]
> Hi,
>
> I am working on an application where an array of ints and
> floats are to
> exported from C++ to Python using boost::python.
>
> As I am newbie to boost python, I couldn't find any documentation or
> working example that satisfies the above requirement. Can
> someone help
> me out??
>
Had similar need some time ago (fetching / setting BLOB values in database).
Ended up making conversion to/from file in C++ code (MFC) and using the
python Array module to import. Hope info below (which is fragments of
working code) is of any use. The class DLBlob is a class providing needed
methods to set/get byte array. Python code would supply the filename to be
used.
Nikolai
//C++ CODE
int PyElement::Blob2File(CString fileName)
{
DLBlob blob = GetBlobValue();
if (!blob.IsEmpty()) {
unsigned char * b = blob.GetBuffer();
CFile theFile(fileName, CFile::modeCreate | CFile::modeWrite
| CFile::typeBinary);
theFile.Write(b, blob.Length());
theFile.Close();
return blob.Length();
}
return 0;
}
int PyElement::File2Blob(CString fileName)
{
CFile theFile(fileName, CFile::modeRead | CFile::typeBinary);
DWORD fileSize = theFile.GetLength();
void *s = ::malloc(fileSize+1);
DWORD count = theFile.Read(s, fileSize);
theFile.Close();
DLBlob blob(count);
blob.InsertBytes(s, count, 0);
SetBlobValue(blob);
return (int)count;
}
int PyElement::BlobSize()
{
DLBlob blob = GetBlobValue();
if (!blob.IsEmpty()) {
return blob.Length();
}
return 0;
}
BOOST_PYTHON_MODULE(CElement)
{
class_<PyElement>("Element")
.def("Blob2File", &PyElement::Blob2File)
.def("File2Blob", &PyElement::File2Blob)
.def("BlobSize", &PyElement::BlobSize)
;
}
More information about the Cplusplus-sig
mailing list