473,666 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to transfer data structure or class from Python to C/C++?

Hi friends,

I am a newer of Python. I want to ask below question:

I have a C/C++ application and I want to use Python as its extension.
To do that, I have to transfer some data structure from C/C++
application to Python and get some data structure from Python to C/C++
application. I have researched Python document, but the example only
describes how to transfer some simple data, such as integer,char,
etc.

Could you please guide me to do that? or tell me some document to have
a research?

Thanks.
Oct 16 '08 #1
10 3471
Hongtian:
Could you please guide me to do that? or tell me some document to have
a research?
You can start googling for:
- SWIG
- Boost.Python
- SIP
- ctypes (built-in module)
- And more.

Bye,
bearophile
Oct 16 '08 #2
On Oct 15, 8:08*pm, Hongtian <hongtian.i...@ gmail.comwrote:
Hi friends,

I am a newer of Python. I want to ask below question:

I have a C/C++ application and I want to use Python as its extension.
To do that, I have to transfer some data structure from C/C++
application to Python and get some data structure from Python to C/C++
application. I have researched Python document, but the example only
describes how to transfer some simple data, such as integer,char,
etc.

Could you please guide me to do that? or tell me some document to have
a research?

Thanks.
Take this for what it's worth. If I understand correctly, you want
this:

struct info {
char* name;
char* address;
int age;
};

int main( ) {
info A, B;
python_run( "\
from urllib import urlget\n\
from mylib import populate_struct \n\
page= urlget( 'http://something' )\n\
populate_struct ( page, A )\n\
populate_struct ( page, B )\n" );
if( A.ageB.age ) {
something_in_C( );
}
return 0;
}

Am I on the right track? Do you have any questions so far?
Oct 16 '08 #3
Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
call PyFunc(struct Tdemo, struct &Tdemo1);
}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.

On Oct 16, 12:09*pm, "Aaron \"Castironpi \" Brady"
<castiro...@gma il.comwrote:
On Oct 15, 8:08*pm, Hongtian <hongtian.i...@ gmail.comwrote:
Hi friends,
I am a newer of Python. I want to ask below question:
I have a C/C++ application and I want to use Python as its extension.
To do that, I have to transfer some data structure from C/C++
application to Python and get some data structure from Python to C/C++
application. I have researched Python document, but the example only
describes how to transfer some simple data, such as integer,char,
etc.
Could you please guide me to do that? or tell me some document to have
a research?
Thanks.

Take this for what it's worth. *If I understand correctly, you want
this:

struct info {
* char* name;
* char* address;
* int age;

};

int main( ) {
* info A, B;
* python_run( "\
from urllib import urlget\n\
from mylib import populate_struct \n\
page= urlget( 'http://something')\n\
populate_struct ( page, A )\n\
populate_struct ( page, B )\n" );
* if( A.ageB.age ) {
* * something_in_C( );
* }
* return 0;

}

Am I on the right track? *Do you have any questions so far?
Oct 16 '08 #4
On Oct 16, 9:10*am, Hongtian <hongtian.i...@ gmail.comwrote:
Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
* * call PyFunc(struct Tdemo, struct &Tdemo1);

}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.
I am stumped. Here's what I have.

/C file:

typedef struct {
int a;
float b;
} TypeA;

static PyObject *
methA(PyObject *self, PyObject *args) {
TypeA a;
TypeA b;
PyObject* fun;
PyObject* res;
TypeA* pa;
TypeA* pb;

PyArg_ParseTupl e( args, "O", &fun );
a.a= 10;
a.b= 20.5;
b.a= 30;
b.b= 40.5;
printf( "%p %p\n", &a, &b );

pa= &a;
pb= &b;

res= PyObject_CallFu nction( fun, "II", &pa, &pb );
Py_DECREF( res );

return PyInt_FromLong( 0 );
}

/Py file:

import ng27ext

import ctypes as c
class TypeA( c.Structure ):
_fields_= [
( 'a', c.c_int ),
( 'b', c.c_float )
]

def exposed( obj1, obj2 ):
print 'in exposed'
print hex( obj1 ), hex( obj2 )
a= c.POINTER( TypeA ).from_address( obj1 )
print a
print a.contents

print ng27ext.methA( exposed )

/Output:

0021FD48 0021FD40
in exposed
0x21fd48 0x21fd40
<ctypes.LP_Type A object at 0x009FF350>
<__main__.Typ eA object at 0x009FF4E0>
0

Which is unexpected. The address on line 4 should be the contents of
'obj1', 0x21fd48, which it's not. I must not be using 'from_address'
properly.
Oct 16 '08 #5
On Oct 16, 9:10*am, Hongtian <hongtian.i...@ gmail.comwrote:
Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
* * call PyFunc(struct Tdemo, struct &Tdemo1);

}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.

On Oct 16, 12:09*pm, "Aaron \"Castironpi \" Brady"

<castiro...@gma il.comwrote:
On Oct 15, 8:08*pm, Hongtian <hongtian.i...@ gmail.comwrote:
Hi friends,
I am a newer of Python. I want to ask below question:
I have a C/C++ application and I want to use Python as its extension.
To do that, I have to transfer some data structure from C/C++
application to Python and get some data structure from Python to C/C++
application. I have researched Python document, but the example only
describes how to transfer some simple data, such as integer,char,
etc.
Could you please guide me to do that? or tell me some document to have
a research?
Thanks.
Did you have any luck?
Oct 17 '08 #6
On Oct 16, 9:10 am, Hongtian <hongtian.i...@ gmail.comwrote:
Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
call PyFunc(struct Tdemo, struct &Tdemo1);

}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.

On Oct 16, 12:09 pm, "Aaron \"Castironpi \" Brady"

<castiro...@gma il.comwrote:
On Oct 15, 8:08 pm, Hongtian <hongtian.i...@ gmail.comwrote:
Hi friends,
I am a newer of Python. I want to ask below question:
I have a C/C++ application and I want to use Python as its extension.
To do that, I have to transfer some data structure from C/C++
application to Python and get some data structure from Python to C/C++
application. I have researched Python document, but the example only
describes how to transfer some simple data, such as integer,char,
etc.
Could you please guide me to do that? or tell me some document to have
a research?
Thanks.
Did you have any luck?
Oct 17 '08 #7
On Oct 16, 9:10*am, Hongtian <hongtian.i...@ gmail.comwrote:
Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
* * call PyFunc(struct Tdemo, struct &Tdemo1);

}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.
snip

Solution produced here. Includes dirty kludge, which will welcome
correction.

/C file:

#include <Python.h>

typedef struct {
int a;
float b;
} TypeA;

static PyObject *
methA(PyObject *self, PyObject *args) {
TypeA a;
TypeA b;
PyObject* fun;
PyObject* res;

PyArg_ParseTupl e( args, "O", &fun );
a.a= 10;
a.b= 20.5;

res= PyObject_CallFu nction( fun, "II", &a, &b );

printf( "%i %f\n", b.a, b.b );
Py_DECREF( res );

return PyInt_FromLong( 0 );
}

static PyMethodDef module_methods[] = {
{"methA", methA, METH_VARARGS, "No doc"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initng27ext(voi d)
{
PyObject* m;
m = Py_InitModule3( "ng27ext", module_methods,
"Custom.");
if (m == NULL)
return;
}

/Py file:

import ng27ext

import ctypes as c
class TypeA( c.Structure ):
_fields_= [
( 'a', c.c_int ),
( 'b', c.c_float )
]

from _ctypes import _cast_addr
_data_cast= c.PYFUNCTYPE( c.py_object, c.c_void_p, c.py_object,
c.py_object)( _cast_addr ) #dirty kludge

def exposed( obj1, obj2 ):
cob1= _data_cast( obj1, None, c.POINTER( TypeA ) )
cob2= _data_cast( obj2, None, c.POINTER( TypeA ) )
print cob1.contents.a , cob1.contents.b
cob2.contents.a = c.c_int( 60 )
cob2.contents.b = c.c_float( 70.5 )
print cob2.contents.a , cob2.contents.b

print ng27ext.methA( exposed )

/Compile & link:

c:/programs/mingw/bin/gcc ng27ext.c -c -Ic:/programs/python25/include
c:/programs/mingw/bin/gcc -shared ng27ext.o -o ng27ext.pyd -Lc:/
programs/python25/libs -lpython25

/Output:

10 20.5
60 70.5
60 70.500000
0
Press any key to continue . . .

Oct 17 '08 #8
En Fri, 17 Oct 2008 20:03:44 -0300, Aaron "Castironpi " Brady
<ca********@gma il.comescribió:
On Oct 16, 9:10*am, Hongtian <hongtian.i...@ gmail.comwrote:
>Not exactly.

In my C/C++ application, I have following function or flow:

void func1(....)
{
* * call PyFunc(struct Tdemo, struct &Tdemo1);

}

I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.

I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.

Thanks.
snip

Solution produced here. Includes dirty kludge, which will welcome
correction.

/C file:

#include <Python.h>

typedef struct {
int a;
float b;
} TypeA;

static PyObject *
methA(PyObject *self, PyObject *args) {
TypeA a;
TypeA b;
PyObject* fun;
PyObject* res;

PyArg_ParseTupl e( args, "O", &fun );
a.a= 10;
a.b= 20.5;

res= PyObject_CallFu nction( fun, "II", &a, &b );

printf( "%i %f\n", b.a, b.b );
Py_DECREF( res );

return PyInt_FromLong( 0 );
}

static PyMethodDef module_methods[] = {
{"methA", methA, METH_VARARGS, "No doc"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initng27ext(voi d)
{
PyObject* m;
m = Py_InitModule3( "ng27ext", module_methods,
"Custom.");
if (m == NULL)
return;
}

/Py file:

import ng27ext

import ctypes as c
class TypeA( c.Structure ):
_fields_= [
( 'a', c.c_int ),
( 'b', c.c_float )
]

from _ctypes import _cast_addr
_data_cast= c.PYFUNCTYPE( c.py_object, c.c_void_p, c.py_object,
c.py_object)( _cast_addr ) #dirty kludge

def exposed( obj1, obj2 ):
cob1= _data_cast( obj1, None, c.POINTER( TypeA ) )
cob2= _data_cast( obj2, None, c.POINTER( TypeA ) )
print cob1.contents.a , cob1.contents.b
cob2.contents.a = c.c_int( 60 )
cob2.contents.b = c.c_float( 70.5 )
print cob2.contents.a , cob2.contents.b

print ng27ext.methA( exposed )

/Compile & link:

c:/programs/mingw/bin/gcc ng27ext.c -c -Ic:/programs/python25/include
c:/programs/mingw/bin/gcc -shared ng27ext.o -o ng27ext.pyd -Lc:/
programs/python25/libs -lpython25

/Output:

10 20.5
60 70.5
60 70.500000
0
Press any key to continue . . .

--
http://mail.python.org/mailman/listinfo/python-list


--
Gabriel Genellina

Oct 21 '08 #9
On Oct 21, 12:46*am, "Gabriel Genellina" <gagsl-...@yahoo.com.a r>
wrote:
En Fri, 17 Oct 2008 20:03:44 -0300, Aaron "Castironpi " Brady *
<castiro...@gma il.comescribió:
On Oct 16, 9:10*am, Hongtian <hongtian.i...@ gmail.comwrote:
Not exactly.
In my C/C++ application, I have following function or flow:
void func1(....)
{
* * call PyFunc(struct Tdemo, struct &Tdemo1);
}
I mean I want to invoke Python function 'PyFunc' and transfer a data
structure 'Tdemo' to this function. After some process in Python, I
want it return 'Tdemo1' back to the C/C++ application.
I research boost.python and think it is not a reasonable solution
because it make the C/C++ application too complex.
Thanks.
snip
Solution produced here. *Includes dirty kludge, which will welcome
correction.
snip
>
--
Gabriel Genellina
Hi Gabriel,
Sorry, did you have some questions about it?
Oct 21 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4431
by: ben moretti | last post by:
hi i'm learning python, and one area i'd use it for is data management in scientific computing. in the case i've tried i want to reformat a data file from a normalised list to a matrix with some sorted columns. to do this at the moment i am using perl, which is very easy to do, and i want to see if python is as easy. so, the data i am using is some epiphyte population abundance data for particular sites, and it looks like this:
4
2401
by: spar | last post by:
I'm converting a Perl script to Python and have run into something I'm not sure how to do in Python. In Perl, I am running through a couple loops and inserting values directly into a complex data structure (array->hash->array). This isn't the actual code, but should demonstrate the general idea: foreach $bar_count(@bars) { foreach $el_count(@els) { $var = somefunc($bar_count,$el_count);
5
4430
by: Claudio Grondi | last post by:
Background information: --------------------------------- in order to monitor mainboard sensory data as fan speeds, temperatures, applications like SpeedFan http://www.almico.com/speedfan.php or MBM http://mbm.livewiredev.com/ can be used. Both of the mentioned apps expose data got from the hardware in a shared memory area.
3
2048
by: Babbit | last post by:
I'm working with a bunch of configuration data that needs to be sent over from a workstation to a server. The old method was to simply memcpy structures into a buffer and send that across, however now I'm trying to use variable sized classes and coming into some difficulty in the copying data to a bytestream without going too crazy. So I ask, what are your experiences/suggestions/help with doing the following: (Pointing me to other...
2
4332
by: RAJ | last post by:
In our multi-tier application, we have several ASP.NET user controls which will update the same data source provided by middle tier logic. In this particular scenario we have one user control displaying the contents of the data source, whilst another control updates the datasource via a command buttons implementation of 'Click', an event raised in the 'Handle Postback Events' stage of the control execution life cycle (via the...
3
2158
by: aurora | last post by:
This is an entry I just added to ASPN. It is a somewhat novel technique I have employed quite successfully in my code. I repost it here for more explosure and discussions. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475158 wy ------------------------------------------------------------------------
3
2394
by: tkirke | last post by:
How does one transfer a buffer object from python -c and back again (assuming the data gets modified)? I can't seem to get this or anything else to work, but am clueless as to what I'm doing wrong using namespace boost::python; static PyObject * proc_buf(PyObject *self, PyObject *args) { PyObject *resultobj;
1
6972
by: Rachel | last post by:
We recently upgraded to ASP.NET 2 AJAX Beta 2 an since we are encountering the following problem: STEPS: 1- navigate to a page containing a UpdatePanel using SERVER.TRANSFER 2- click on a button (regardless of type: button, linkButton, imageButton) 3- (first) async call works fine 4 - click again to make second async call and somehow the page path becomes
4
4624
by: Luvin lunch | last post by:
Hi, I've developed a worklist system in Access and I plan to deploy four copies of it to the four users that need it. I said I'll be deploying copies because there is no shared network in the cave I'm working in. Each of the users will have their own copy and work on it on their own machines. It's so 1989 I dunno what to do with myself. Anyway, the manager wants to get a copy of each user's data once a month. So to my problem. I...
0
8444
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8869
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7386
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1775
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.