473,287 Members | 1,708 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

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

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 5506
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
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. ...
0
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...
23
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...
4
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...
1
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...
2
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...
1
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...
6
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...
0
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...
0
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.