[Tutor] Get the structure values from a c file

Alan Gauld alan.gauld at btinternet.com
Mon Dec 17 09:41:05 CET 2012


On 17/12/12 03:12, Marefe Serentas wrote:

> I want to create a python script that will store the value of the
> structure /MainStruct/ from the c file.

You will need to be a lot more specific about your requirements.
A structure is a data definition, it does not have a value.
It is like saying you want to store the value of char.
Secondly what do you mean by "from the C file"? Do you
mean you want extract the value from the C source file?
Or do you mean the data is stored elsewhere and you want
to use the definition in the C file to interpret the data?
In which case where/how is the data stored?

> Suppose my c file looks like this:
> ----------------------------------------------------------
snip
> typedef struct MainStruct
> {
> }Main;
>
> void generate()
> {
>      MainStruct myMain = {0};

Is this valid C?
I'd have expected either

struct MainStruct myMain

or

Main myMain

But my C is a bit rusty...
But if I'm right please post runnable code otherwise we are all guessing.


>      myMain.var1.a = 1
>      myMain.var1.b = 'a'
>      myMain.var2 = 3
>      myMain.var3[0] = -3
>      myMain.var3[1] = 6
>      myMain.var3[2] = 18
> }


> My python script accepts a c file as input.
> How can I get the values of the structure?

I assume you really mean the values of the myMain variable?
But taking the C file as input makes no sense since C files are
normally compiled and the resulting binary file executed.
So taking the C file as input would imply you want to
parse the C source, which you can do more easily by just
reading it!

> Can I call the function generate() in python script, but it doesn't have
> a return statement, how can I get the values by calling the function?

You can't call generate() because its not compiled into executable form. 
All you have is a text file full of C source code. If you have access to 
the executable there are ways of calling the function
but since it always stores the same values there seems little point.

> Help me, I'm really new in python.

Are you also new in C?
Why are you doing this, there is presumably a bigger problem behind this 
because as it stands it makes no sense.

> All I could think is just parse the c file. But it seems that it's not a
> good idea.

The best parser in this case is your brain.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list