473,564 Members | 2,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About Python's C API

Dear sir,

I am used to developing C program on MSVC7.0 platform.
This is my first time to use Python for calling by C program.
Now, it is hard to deal with the problem about extracting the variable
which be definied in Python. That how can I do?

I have gotten the JPython 's sample that the following code can be looked.
Have anyone help me to obtain same results that be called by Python's C API?
What do I mean?

See attached the following code.

// JPython code
=============== =============== =========
import org.python.util .PythonInterpre ter;
import org.python.core .*;

public class SimpleEmbedded {
public static void main(String []args)
throws PyException
{
PythonInterpret er interp =
new PythonInterpret er();

System.out.prin tln("Hello, brave new world");
interp.exec("im port sys");
interp.exec("pr int sys");

interp.set("a", new PyInteger(42));
interp.exec("pr int a");
interp.exec("x = 2+2");
PyObject x = interp.get("x") ;

System.out.prin tln("x: "+x);
System.out.prin tln("Goodbye, cruel world");
}
}
I would like to re-write those program to Python.

// C Language code =============== ===============
void main() {
Py_Initialize() ;
printf("Hello, brave new world");

PyRun_SimpleStr ing("import sys");
PyRun_SimpleStr ing("print sys");
// interp.set("a", new PyInteger(42));

PyRun_SimpleStr ing("print a");
PyRun_SimpleStr ing("x = 2+2");
// PyObject x = interp.get("x") ;
// System.out.prin tln("x: "+x);

Py_Finalize();
printf("Goodbye , cruel world");
}

See the above C Language code,

After running the statement PyRun_SimpleStr ing("x = 2+2"),
the variable x can be definied and be assigned value 4 in Python.

Meanwhile, next one, I would like to get the x porinter.

Could you help me how can I do?
Or show me the other way to reach my purpose.

Sincerely yours,
Link
Jul 18 '05 #1
3 5116
Let me start by saying I'm not a pro with the C API of Python.

With PyRun_SimpleStr ing(), everything takes place in the special
__main__ module:
PyRun_SimpleStr ingFlags(const char *command, PyCompilerFlags *flags)
{
PyObject *m, *d, *v;
m = PyImport_AddMod ule("__main__") ;
if (m == NULL)
return -1;
d = PyModule_GetDic t(m);
v = PyRun_StringFla gs(command, Py_file_input, d, d, flags);
if (v == NULL) {
PyErr_Print();
return -1;
}
Py_DECREF(v);
if (Py_FlushLine() )
PyErr_Clear();
return 0;
}

So, to get the attribute x from __main__, convert it to a string, and
printf() it, you'd use this sequence [all untested]:
PyObject *m, *d, *x, *s;

/* m is a "new" reference */
m = PyImport_AddMod ule("__main__") ;
if (m == NULL)
return -1;
/* d is a "borrowed" reference */
d = PyModule_GetDic t(m);
Py_DECREF(m); m = NULL; /* Done with m -- decref and set to NULL */
x = PyDict_GetItemS tring(d, "x")
/* x is a "borrowed" reference */
if (x == NULL) {
PyErr_Print();
return;
}
/* s is a "new" reference */
s = PyObject_Str(x) ;
if (s == NULL) {
PyErr_Print();
return;
}
printf("x: %s\n", PyString_AsStri ng(s));
Py_DECREF(s); s = NULL; /* Done with s -- decref and set to NULL */

If you're programming in C++, you might benefit from checking out boost.python at
http://boost.org/libs/python/doc/index.html
I'm not actually a boost.python user, but I've heard good things about it.

Jeff

Jul 18 '05 #2
Jeff,

First, I need to say you are so smart.
I really appreciated your help that of course good idea to solve about my
extraction's prblem.

Following your advise, i obtained the value of variable from Python in
developing C/API.

By the way, if I had added the statement "Py_DECREF( m); m = NULL;",
It would be crash during running program.
So that need to remove this statement.

Shall I ask you any problem if no this statment at here?
Any trouble will be happened?

With best regards.
Link

"Jeff Epler" <je****@unpytho nic.net>
???????:ma***** *************** *************@p ython.org...
Let me start by saying I'm not a pro with the C API of Python.

With PyRun_SimpleStr ing(), everything takes place in the special
__main__ module:
PyRun_SimpleStr ingFlags(const char *command, PyCompilerFlags *flags)
{
PyObject *m, *d, *v;
m = PyImport_AddMod ule("__main__") ;
if (m == NULL)
return -1;
d = PyModule_GetDic t(m);
v = PyRun_StringFla gs(command, Py_file_input, d, d, flags);
if (v == NULL) {
PyErr_Print();
return -1;
}
Py_DECREF(v);
if (Py_FlushLine() )
PyErr_Clear();
return 0;
}

So, to get the attribute x from __main__, convert it to a string, and
printf() it, you'd use this sequence [all untested]:
PyObject *m, *d, *x, *s;

/* m is a "new" reference */
m = PyImport_AddMod ule("__main__") ;
if (m == NULL)
return -1;
/* d is a "borrowed" reference */
d = PyModule_GetDic t(m);
Py_DECREF(m); m = NULL; /* Done with m -- decref and set to NULL */
x = PyDict_GetItemS tring(d, "x")
/* x is a "borrowed" reference */
if (x == NULL) {
PyErr_Print();
return;
}
/* s is a "new" reference */
s = PyObject_Str(x) ;
if (s == NULL) {
PyErr_Print();
return;
}
printf("x: %s\n", PyString_AsStri ng(s));
Py_DECREF(s); s = NULL; /* Done with s -- decref and set to NULL */

If you're programming in C++, you might benefit from checking out boost.python at http://boost.org/libs/python/doc/index.html
I'm not actually a boost.python user, but I've heard good things about it.

Jeff

Jul 18 '05 #3
Link wrote:
Dear sir,

I am used to developing C program on MSVC7.0 platform.
This is my first time to use Python for calling by C program.

Much easier to use swig than to code that sort of thing directly.

www.swig.org
Jul 18 '05 #4

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

Similar topics

220
18879
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it...
54
6524
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature...
3
2816
by: fdsl ysnh | last post by:
--- python-list-request@python.orgдµÀ: > Send Python-list mailing list submissions to > python-list@python.org > > To subscribe or unsubscribe via the World Wide Web, > visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body > 'help' to
17
1638
by: Jan Danielsson | last post by:
Hello all, I recently started using Python, and I must say I like it. Both the language and libraries available for it. Background: I have written an application which I use to keep track of my personal economy. I wrote it in Java because I wanted to learn the language for a course in programming at my university. Now that I have...
97
4322
by: Cameron Laird | last post by:
QOTW: "Python makes it easy to implement algorithms." - casevh "Most of the discussion of immutables here seems to be caused by newcomers wanting to copy an idiom from another language which doesn't have immutable variables. Their real problem is usually with binding, not immutability." - Mike Meyer Among the treasures available in The...
23
2289
by: Ray | last post by:
Hello! I've been reading about PyPy, but there are some things that I don't understand about it. I hope I can get some enlightenment in this newsgroup :) First, the intro: <excerpt> "The PyPy project aims at producing a flexible and fast Python
161
7751
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.. (After reading that
65
4157
by: Steven Watanabe | last post by:
I know that the standard idioms for clearing a list are: (1) mylist = (2) del mylist I guess I'm not in the "slicing frame of mind", as someone put it, but can someone explain what the difference is between these and: (3) mylist =
17
2692
by: Eric_Dexter | last post by:
def simplecsdtoorc(filename): file = open(filename,"r") alllines = file.read_until("</CsInstruments>") pattern1 = re.compile("</") orcfilename = filename + "orc" for line in alllines: if not pattern1 print >>orcfilename, line I am pretty sure my code isn't close to what I want. I need to be able
21
1908
by: Roy Smith | last post by:
I'm working on a product which for a long time has had a Perl binding for our remote access API. A while ago, I wrote a Python binding on my own, chatted it up a bit internally, and recently had a (large) customer enquire about getting access to it. I asked for permission to distribute the Python binding, and after a few weeks of winding...
0
7583
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...
0
7888
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. ...
1
7642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5484
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...
0
5213
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...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
924
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...

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.