473,385 Members | 1,555 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,385 software developers and data experts.

Problem with embedding python in c++.

1
Hello, I'm quite new to Python and embedding python in c++. I'm trying to write a function that i can use to call a python function. It should take 3 arguments, the name of the python file, the python function name and a std:vector with arguments for the python function. This is my code:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     string arg1 = "runme"; //name of python file
  4.     string arg2 = "sub"; // name of python function
  5.  
  6.     Py_Initialize();
  7.  
  8.     vector<string> arguments;
  9.     arguments.push_back("100");
  10.     arguments.push_back("10");
  11.  
  12.     callPython(arg1,arg2,arguments);
  13.  
  14.     Py_Finalize(); // crash here
  15.  
  16.     return 1;
  17. }
  18.  
Expand|Select|Wrap|Line Numbers
  1. void callPython(string py_file, string py_function, vector<string> args)
  2. {
  3.     int i;
  4.     PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
  5.  
  6.     // Build the name object
  7.     pName = PyString_FromString( py_file.c_str() );
  8.  
  9.     // Load the module object
  10.     pModule = PyImport_Import(pName);
  11.  
  12.     // pDict is a borrowed reference 
  13.     pDict = PyModule_GetDict(pModule);
  14.  
  15.     // pFunc is also a borrowed reference 
  16.     pFunc = PyDict_GetItemString(pDict, py_function.c_str() );
  17.  
  18.     if (PyCallable_Check(pFunc)) 
  19.     {
  20.         pValue = PyObject_CallObject(pFunc, NULL);//måste returna något tex 1
  21.  
  22.         // Prepare the argument list for the call
  23.         if( args.size() > 0 )
  24.         {
  25.                 pArgs = PyTuple_New(args.size());
  26.                 for (i = 0; i < args.size(); i++)
  27.                 {
  28.                     pValue = PyInt_FromLong(atoi(args[i].c_str()));
  29.                     if (!pValue)
  30.                     {                        
  31.                         PyErr_Print();
  32.                     }
  33.                     PyTuple_SetItem(pArgs, i, pValue);    
  34.                 }
  35.  
  36.                 pValue = PyObject_CallObject(pFunc, pArgs);
  37.  
  38.                 if (pArgs != NULL)
  39.                 {
  40.                     Py_DECREF(pArgs);
  41.                 }
  42.         } else
  43.         {
  44.                 pValue = PyObject_CallObject(pFunc, NULL);
  45.         }
  46.  
  47.         if (pValue != NULL) 
  48.         {
  49.             Py_DECREF(pValue);
  50.         }
  51.         else 
  52.         {
  53.             PyErr_Print();
  54.         }
  55.     } else 
  56.     {
  57.         PyErr_Print();
  58.     }
  59.  
  60.     // Clean up
  61.     Py_DECREF(pModule);
  62.     Py_DECREF(pName);
  63. }
  64.  
And the python file (runme.py):
Expand|Select|Wrap|Line Numbers
  1. def sub(a,b):
  2.     print a-b
  3.     return 0
  4.  
Now to the problem. It does print out the proper result (90 in this case) so it calls the python function. But I get an error and it crashes when at Py_Finalize() in main.

I get the following error:
Expand|Select|Wrap|Line Numbers
  1. Exception exceptions.TypeError: 'sub() takes exactly 2 arguments (0 given)' in 'garbage collection' ignored
  2. Fatal Python error: unexpected exception during garbage collection
  3.  
What have i done wrong? I did get it to work with adding PyErr_Clear(); before Py_Finalize() but that doesnt seem like the right thing to do?

I'm using Python 2.5.1, Windows XP pro and VS2005.

Thanks
Dec 19 '07 #1
1 2546
Have you tried called PyErr_Print() before Py_Finalize() to ensure that there are no other errors?
Mar 10 '08 #2

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

Similar topics

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...
0
by: adsheehan | last post by:
Hi, I am embedding Python into a multi-threaded C++ application runnig on Solaris and need urgent clarification on the embedding architecture and its correct usage (as I am experience weird...
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...
1
by: Tommy Nordgren | last post by:
I want to write an application that embeds and extends (at least) the Python and Perl interpreters. Now i want to find as much as possible about the Python tools used for extending and embedding...
6
by: John Dean | last post by:
Hi I spent the whole of yesterday trying the get the following C code to execute PyRun_String("def title();", Py_file_input, dict, dict); PyRun_String("\treturn 'Foo Bar'", Py_file_input,...
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: DevEng | last post by:
Hi all, I am new to Python and trying to embed it into a c/c++ application. I started with examples from the documentation pages and go to the Pure Embedding example...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.