473,786 Members | 2,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Embedding Python in C/C++ using Python/C API

6 New Member
Hello,
I've been researching how to embed python into C/C++. And, I learned how to write c/c++ code that, in threory, should do its job in embedding Python module into itself.
Here is what I have..

Expand|Select|Wrap|Line Numbers
  1. #include <python2.4/Python.h>
  2. void SomeStuff::someMethod  (void) {
  3.         std::cout << "ErrVisitor" << std::endl;
  4.  
  5.         PyObject *pName, *pModule, *pDict, *pFunc;
  6.  
  7.         Py_Initialize();
  8.         std::cout << "1" << std::endl;
  9.         pName = PyString_FromString ("mailSender");
  10.         std::cout << "2" << std::endl;
  11.         pModule = PyImport_Import (pName);
  12.         std::cout << "3" << std::endl;
  13.         if (PyModule_Check(pModule)) {
  14.                 std::cout << "Module" << std::endl;
  15.         } else {
  16.                 std::cout << "Not a Module" << std::endl;
  17.                 exit(2);
  18.         }
  19.         std::cout << "4" << std::endl;
  20.         pDict = PyModule_GetDict (pModule);
  21.         pFunc = PyDict_GetItemString(pDict, "send_mail");
  22.  
  23.         if (PyCallable_Check(pFunc)) {
  24.                 PyObject_CallObject(pFunc, NULL);
  25.         } else {
  26.                 std::cout << "Not Callable" << std::endl;
  27.                 PyErr_Print ();
  28.         }
  29. Py_DECREF (pModule);
  30.         Py_DECREF (pName);
  31.  
  32.         Py_Finalize();
  33. }
with the following python code: mailSender.py

Expand|Select|Wrap|Line Numbers
  1. import smtplib
  2. import os
  3. from email.MIMEMultipart import MIMEMultipart
  4. from email.MIMEBase import MIMEBase
  5. from email.MIMEText import MIMEText
  6. from email.Utils import COMMASPACE, formatdate
  7. from email import Encoders
  8.  
  9. def send_mail ():
  10.     send_from = "jin@sohovfx.com";
  11.     send_to = []
  12.     send_to.append ("jin@sohovfx.com")
  13.     subject = "hihihi"
  14.     text = "hihihihihi"
  15.     files = [];
  16.     files.append ('/home/jin/Workspace/scabs/old_split.py');
  17.     server = "smtp.beanfield.com"
  18.  
  19.     assert type(send_to)==list
  20.     assert type(files)==list
  21.  
  22.     msg = MIMEMultipart()
  23.     msg['From'] = send_from
  24.     msg['To'] = COMMASPACE.join(send_to)
  25.     msg['Date'] = formatdate(localtime=True)
  26.     msg['Subject'] = subject
  27.  
  28.     msg.attach( MIMEText(text) )
  29.  
  30.     for file in files:
  31.         part = MIMEBase('application', "octet-stream")
  32.         part.set_payload( open(file,"rb").read() )
  33.         Encoders.encode_base64(part)
  34.         part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
  35.         msg.attach(part)
  36.  
  37.     smtp = smtplib.SMTP(server)
  38.     smtp.sendmail(send_from, send_to, msg.as_string())
  39.     smtp.close()
  40.  
Both Codes are in the same directory, and I use
"g++ SomeCode.h SomeCode.cc -lpython2.4"
to compile my code...

I run with ./a.out,
and the output is the following:

ErrVisitor
1
2
3
Segmentation fault

..
I think the module didnt get imported? How do I make sure that the module DOES get imported? Do I need to do something else at the time of compilation to link these two codes?
Why am I getting a Seg fault?

Any help or insight would be greatly appreciated..

Thank you.
Nov 1 '07 #1
1 5540
openuser
6 New Member
Solved.

Please look at the bottom of this page:
Embedding Python in C/C++: Part I
Nov 1 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2515
by: jordi | last post by:
Hi, I'm starting to use Python embedded in a C program. I'm using Python to execute several scripts using as a variables information retrieved for several multithread "agents" written in C. The method is: 1- Create a thread for each agent (I use a pool thread, every agent run in a different thread) 2- Precompile a different script for each agent. 3- Make the agent retrieve its data
0
1850
by: Atul Kshirsagar | last post by:
I am embedding python in my C++ application. I am using Python *2.3.2* with a C++ extention DLL in multi-threaded environment. I am using SWIG-1.3.19 to generate C++ to Python interface. Now to explain it in details, 1. Python initialization and finalization is done in the *main* thread. 2. For each new thread I create a separate sub-interpreter . 3. Using PyRun_String("import myModule"...) before execution of python
23
2985
by: Robey Holderith | last post by:
Anyone know a good way to embed python within python? Now before you tell me that's silly, let me explain what I'd like to do. I'd like to allow user-defined scriptable objects. I'd like to give them access to modify pieces of my classes. I'd like to disallow access to pretty much the rest of the modules.
4
2790
by: Alicia Haumann | last post by:
I accidentally sent this to webmaster@python.org, so this could be a duplicate if "webmaster" forwards it to this list. :{ Hi, there. Thanks for any help that can be offered. I've been working with Python for a year or more now, but only doing simple extending in C/C++. I'm now attempting some embedding and several questions have come to mind. BTW - I'm running Windows 2000 with Python23 and VisualC++ developers
1
537
by: Martin | last post by:
Greetings, I am new to python and wish to embed python in an 3D graphics application to provide application automation. The high level goal is to be able to drive my app from a script for batch job like behavior rather than via the GUI (ie. I would like to run a script and see those changes reflected in the GUI as if the user had clicked buttons, etc.) The application is written in C++ and uses QT for the GUI. I have read the python...
2
2870
by: Roose | last post by:
With some googling I have found these resources: http://docs.python.org/ext/win-dlls.html http://www.python.org/doc/faq/windows.html I have a large Win32/MFC/C/C++ application that has an embedded scripting language (a very limited one). I would like to rip it out and replace it with Python. I am thinking that this would be relatively simple since the scripting language is a very small interface between the UI and the engine --...
1
1920
by: amit | last post by:
Hello, I am currently studying how to embedd python. I am developing a graphical C++ application. My goal is to embedd python script that will control some kind of animation. I have some questions about python embedding: 1) Is there a good text book or other resource on embedding/extending? (I find it hard to learn only by the tutorial and C/Python API from the python.org site)
6
3009
by: Qun Cao | last post by:
Hi Everyone, I am a beginner on cross language development. My problem at hand is to build a python interface for a C++ application built on top of a 3D game engine. The purpose of this python interface is providing a convenient scripting toolkit for the application. One example is that a user can write a python script like: player = Player() game.loadPlayer(player) player.moveTo(location)
0
2142
by: Kenneth McDonald | last post by:
Sorry for crossposting to several lists, but from what I can tell, what I want to do may involve several different areas of expertise. (None of which I have :-( ) I'd like to use Gecko as the UI for an application mostly implemented in Python. Ideally, I'd like to somehow come up with a Python module that wraps the Gecko, so that I can: 1) Create windows whose content is drawn by Gecko. 1) Dynamically manipulate what is shown by Gecko.
0
2115
by: Tim Spens | last post by:
--- On Fri, 6/27/08, Tim Spens <t_spens@yahoo.comwrote: I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via callback.setHandler1(callback1) this only seems to affect pythons ability to trigger an "event" in c. PyObject *Handler is always NULL even after I call Register_Handler(...). I thought there was some magic here that was assigning the pointer *Handler to my python...
0
9497
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
10363
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
10164
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
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8992
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
7515
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
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
3
2894
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.