473,499 Members | 1,974 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.PythonInterpreter;
import org.python.core.*;

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

System.out.println("Hello, brave new world");
interp.exec("import sys");
interp.exec("print sys");

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

System.out.println("x: "+x);
System.out.println("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_SimpleString("import sys");
PyRun_SimpleString("print sys");
// interp.set("a", new PyInteger(42));

PyRun_SimpleString("print a");
PyRun_SimpleString("x = 2+2");
// PyObject x = interp.get("x");
// System.out.println("x: "+x);

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

See the above C Language code,

After running the statement PyRun_SimpleString("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 5103
Let me start by saying I'm not a pro with the C API of Python.

With PyRun_SimpleString(), everything takes place in the special
__main__ module:
PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
{
PyObject *m, *d, *v;
m = PyImport_AddModule("__main__");
if (m == NULL)
return -1;
d = PyModule_GetDict(m);
v = PyRun_StringFlags(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_AddModule("__main__");
if (m == NULL)
return -1;
/* d is a "borrowed" reference */
d = PyModule_GetDict(m);
Py_DECREF(m); m = NULL; /* Done with m -- decref and set to NULL */
x = PyDict_GetItemString(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_AsString(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****@unpythonic.net>
???????:ma*********************************@python .org...
Let me start by saying I'm not a pro with the C API of Python.

With PyRun_SimpleString(), everything takes place in the special
__main__ module:
PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
{
PyObject *m, *d, *v;
m = PyImport_AddModule("__main__");
if (m == NULL)
return -1;
d = PyModule_GetDict(m);
v = PyRun_StringFlags(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_AddModule("__main__");
if (m == NULL)
return -1;
/* d is a "borrowed" reference */
d = PyModule_GetDict(m);
Py_DECREF(m); m = NULL; /* Done with m -- decref and set to NULL */
x = PyDict_GetItemString(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_AsString(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
18799
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...
54
6497
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...
3
2809
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 >...
17
1630
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...
97
4280
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...
23
2276
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...
161
7679
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.....
65
4131
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...
17
2682
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...
21
1899
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...
0
7131
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,...
0
7007
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...
0
7174
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,...
1
6894
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...
0
5470
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,...
0
3099
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...
0
3091
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
297
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...

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.