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
- #include <python2.4/Python.h>
- void SomeStuff::someMethod (void) {
- std::cout << "ErrVisitor" << std::endl;
- PyObject *pName, *pModule, *pDict, *pFunc;
- Py_Initialize();
- std::cout << "1" << std::endl;
- pName = PyString_FromString ("mailSender");
- std::cout << "2" << std::endl;
- pModule = PyImport_Import (pName);
- std::cout << "3" << std::endl;
- if (PyModule_Check(pModule)) {
- std::cout << "Module" << std::endl;
- } else {
- std::cout << "Not a Module" << std::endl;
- exit(2);
- }
- std::cout << "4" << std::endl;
- pDict = PyModule_GetDict (pModule);
- pFunc = PyDict_GetItemString(pDict, "send_mail");
- if (PyCallable_Check(pFunc)) {
- PyObject_CallObject(pFunc, NULL);
- } else {
- std::cout << "Not Callable" << std::endl;
- PyErr_Print ();
- }
- Py_DECREF (pModule);
- Py_DECREF (pName);
- Py_Finalize();
- }
Expand|Select|Wrap|Line Numbers
- import smtplib
- import os
- from email.MIMEMultipart import MIMEMultipart
- from email.MIMEBase import MIMEBase
- from email.MIMEText import MIMEText
- from email.Utils import COMMASPACE, formatdate
- from email import Encoders
- def send_mail ():
- send_from = "jin@sohovfx.com";
- send_to = []
- send_to.append ("jin@sohovfx.com")
- subject = "hihihi"
- text = "hihihihihi"
- files = [];
- files.append ('/home/jin/Workspace/scabs/old_split.py');
- server = "smtp.beanfield.com"
- assert type(send_to)==list
- assert type(files)==list
- msg = MIMEMultipart()
- msg['From'] = send_from
- msg['To'] = COMMASPACE.join(send_to)
- msg['Date'] = formatdate(localtime=True)
- msg['Subject'] = subject
- msg.attach( MIMEText(text) )
- for file in files:
- part = MIMEBase('application', "octet-stream")
- part.set_payload( open(file,"rb").read() )
- Encoders.encode_base64(part)
- part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
- msg.attach(part)
- smtp = smtplib.SMTP(server)
- smtp.sendmail(send_from, send_to, msg.as_string())
- smtp.close()
"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.