Embedding python in C

2005-06-28 Thread Philippe C. Martin
Hi,

Is there a program out there that would generate the C code to instantiate
objects and call them:

ex: miracle.exe -i mymodule.py -o module_internface.c ?

I seem to recall a _yes_ to that but I got a memory overflow :-)

Thanks,

Philippe
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in C

2007-06-04 Thread mistabean
Hello,

first of all, I am a programming newbie, especially in python...

Onwards to the problem, I have been having difficulty embedding a
python module into my C/C++ program. (just a test program before
moving on into the real thing). I have been making test runs using the
codes from http://docs.python.org/ext/pure-embedding.html as a basic,
but modifiying it now as a function inside my C/C++ code.

Problem started when I started passing an array as an argument. The
module also need an array as an argument, but somehow I can't make
them to go pass the "input-error checking" of the module.

The code for argument building and calling are as follows:

void CallSnake(char ModName[], char FuncName[], double result[])
{
  ...
  /*Some operations to import modname, and preping FuncName, all is
ok*/
  ...
  /*Processing the result array and calling the function, problem
time*/
pArgs = PyTuple_New(MAX_ELEMENT);
pArg = PyList_New(1);
for (i = 0; i < MAX_ELEMENT; ++i)
{
 pValue = Py_BuildValue("d", result[i]);
 PyTuple_SetItem(pArgs, i, pValue);

 if (!(*pArgs).ob_refcnt)
 {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return;
 }
 }

 PyList_SetItem(pArg, 0, pArgs);
 pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL);
   /*Some more checking and DECREFing occurs here*/
 }

Error I have been getting is:

Traceback
   if x.ndim != 1; /*x is the input array, checking if it's a 1D*/
AttributeError: 'list' object has no attribute 'ndim'

I have been trying many call variations, but alas, I think the problem
lies in the list building process. I have no problems calling a non-
arrayed (albeit,still single) argument.

Thanks in advance...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python in C

2005-06-28 Thread Chris Lambacher
pyrex can be used for embedding too.
http://www.freenet.org.nz/python/embeddingpyrex/

On 6/28/05, Philippe C. Martin <[EMAIL PROTECTED]> wrote:
> Actually maybe not ... looking at the doc:
> 
> I have modules already coded in Python, and I need a C wrapper so C
> applications may link with it.
> 
> Regards,
> 
> Philippe
> 
> 
> 
> On Tuesday 28 June 2005 04:53 pm, Philippe C. Martin wrote:
> > Sounds like it, thanks.
> >
> > Philippe
> >
> > On Tuesday 28 June 2005 09:10 pm, Chris Lambacher wrote:
> > > Pyrex might be what you are looking for:
> > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
> > >
> > > -Chris
> > >
> > > On 6/28/05, Philippe C. Martin <[EMAIL PROTECTED]> wrote:
> > > > Hi,
> > > >
> > > > Is there a program out there that would generate the C code to
> > > > instantiate objects and call them:
> > > >
> > > > ex: miracle.exe -i mymodule.py -o module_internface.c ?
> > > >
> > > > I seem to recall a _yes_ to that but I got a memory overflow :-)
> > > >
> > > > Thanks,
> > > >
> > > > Philippe
> > > > --
> > > > http://mail.python.org/mailman/listinfo/python-list
> 
> --
> *
> Philippe C. Martin
> SnakeCard, LLC
> www.snakecard.com
> +1 405 694 8098
> *
> 


-- 
Christopher Lambacher
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python in C

2005-06-28 Thread Philippe C. Martin
Thanks, I cannot get the demo to compile, but I joined their list.

Thanks

Philippe



Chris Lambacher wrote:

> pyrex can be used for embedding too.
> http://www.freenet.org.nz/python/embeddingpyrex/
> 
> On 6/28/05, Philippe C. Martin <[EMAIL PROTECTED]> wrote:
>> Actually maybe not ... looking at the doc:
>> 
>> I have modules already coded in Python, and I need a C wrapper so C
>> applications may link with it.
>> 
>> Regards,
>> 
>> Philippe
>> 
>> 
>> 
>> On Tuesday 28 June 2005 04:53 pm, Philippe C. Martin wrote:
>> > Sounds like it, thanks.
>> >
>> > Philippe
>> >
>> > On Tuesday 28 June 2005 09:10 pm, Chris Lambacher wrote:
>> > > Pyrex might be what you are looking for:
>> > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
>> > >
>> > > -Chris
>> > >
>> > > On 6/28/05, Philippe C. Martin <[EMAIL PROTECTED]> wrote:
>> > > > Hi,
>> > > >
>> > > > Is there a program out there that would generate the C code to
>> > > > instantiate objects and call them:
>> > > >
>> > > > ex: miracle.exe -i mymodule.py -o module_internface.c ?
>> > > >
>> > > > I seem to recall a _yes_ to that but I got a memory overflow :-)
>> > > >
>> > > > Thanks,
>> > > >
>> > > > Philippe
>> > > > --
>> > > > http://mail.python.org/mailman/listinfo/python-list
>> 
>> --
>> *
>> Philippe C. Martin
>> SnakeCard, LLC
>> www.snakecard.com
>> +1 405 694 8098
>> *
>> 
> 
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in C++ Problem

2006-05-09 Thread gavinpaterson
Dear Pythoners,

I am trying to embed a Python script into a C++ application for the
first time.

Although I have used the example 5.3 Pure Embedding I am having
problems with calling the function defined in my program.

If I define function multiply in module "multiply.py"

def multiply(a,b):
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c

Then call the program with the following arguments:

multiply multiply 2 3

Then I'd expect to see the result appear in stdout. The compiled
module is found but the program fails to get past:

if (pFunc && PyCallable_Check(pFunc))

I am using VC7.1 on windows XP. Where am I going wrong?






-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in C/C++

2006-08-09 Thread kingcrustybun
Not a Python newb but a bit out of my depth here...

We are trying to use the Python interpreter from within a C/C++
aplication to execute Python code which is in an external file. The
idea is to share a dictionary between the C app and the python script.
After Py_Initialize()

we do something like (ignoring checks)
p_module = PyImport_ImportModule("moduleX");
p_dict = PyDict_New();

Then, to add the dictionary we use
PyModule_AddObject(p_module, "dictName", p_dict);
Which fails.

I was expecting to see an empty dictionary called "dictName" in the
list of variables when i execute vars() in the imported python script.

Is the approach at least correct?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C

2007-06-04 Thread Gabriel Genellina
En Mon, 04 Jun 2007 11:58:38 -0300, <[EMAIL PROTECTED]> escribió:

> Onwards to the problem, I have been having difficulty embedding a
> python module into my C/C++ program. (just a test program before
> moving on into the real thing). I have been making test runs using the
> codes from http://docs.python.org/ext/pure-embedding.html as a basic,
> but modifiying it now as a function inside my C/C++ code.
>
> Problem started when I started passing an array as an argument. The
> module also need an array as an argument, but somehow I can't make
> them to go pass the "input-error checking" of the module.
>
> The code for argument building and calling are as follows:
>
> void CallSnake(char ModName[], char FuncName[], double result[])
> {
>   ...
>   /*Some operations to import modname, and preping FuncName, all is
> ok*/
>   ...
>   /*Processing the result array and calling the function, problem
> time*/
> pArgs = PyTuple_New(MAX_ELEMENT);

Should check for a NULL return value.

> pArg = PyList_New(1);

Same here.

> for (i = 0; i < MAX_ELEMENT; ++i)
> {
>  pValue = Py_BuildValue("d", result[i]);

I'd use PyFloat_FromDouble here.

>  PyTuple_SetItem(pArgs, i, pValue);
>
>  if (!(*pArgs).ob_refcnt)

What do you expect from this? pArgs is a newly created tuple - unless you  
DECREF it explicitely, ob_refcnt should never be 0. (Also, the -> operator  
exists for exactly this usage).

>  PyList_SetItem(pArg, 0, pArgs);
>  pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL);

You didn't show us how you got pFunc here. Just to make it clear, you are  
calling pFunc with a single argument, which is a list that contains a  
single element, which is a tuple containing exactly MAX_ELEMENT float  
objects.

> Traceback
>if x.ndim != 1; /*x is the input array, checking if it's a 1D*/
> AttributeError: 'list' object has no attribute 'ndim'

Python lists don't have a ndim attribute. Perhaps you want some kind of  
Numeric array? (ndarray?)

> I have been trying many call variations, but alas, I think the problem
> lies in the list building process. I have no problems calling a non-
> arrayed (albeit,still single) argument.

Yes, it appears that you are building a plain list but your code is  
expecting another kind of object. I'm unfamiliar with Numeric arrays, if  
that is what you need; perhaps someone else can help, or ask again in a  
Numeric-specific list.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C

2007-06-04 Thread mistabean
On 5 Jun., 01:32, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Mon, 04 Jun 2007 11:58:38 -0300, <[EMAIL PROTECTED]> escribió:
>
>
>
>
>
> > Onwards to the problem, I have been having difficulty embedding a
> > python module into my C/C++ program. (just a test program before
> > moving on into the real thing). I have been making test runs using the
> > codes fromhttp://docs.python.org/ext/pure-embedding.htmlas a basic,
> > but modifiying it now as a function inside my C/C++ code.
>
> > Problem started when I started passing an array as an argument. The
> > module also need an array as an argument, but somehow I can't make
> > them to go pass the "input-error checking" of the module.
>
> > The code for argument building and calling are as follows:
>
> > void CallSnake(char ModName[], char FuncName[], double result[])
> > {
> >   ...
> >   /*Some operations to import modname, and preping FuncName, all is
> > ok*/
> >   ...
> >   /*Processing the result array and calling the function, problem
> > time*/
> > pArgs = PyTuple_New(MAX_ELEMENT);
>
> Should check for a NULL return value.
>
> > pArg = PyList_New(1);
>
> Same here.
>
> > for (i = 0; i < MAX_ELEMENT; ++i)
> > {
> >  pValue = Py_BuildValue("d", result[i]);
>
> I'd use PyFloat_FromDouble here.
>
> >  PyTuple_SetItem(pArgs, i, pValue);
>
> >  if (!(*pArgs).ob_refcnt)
>
> What do you expect from this? pArgs is a newly created tuple - unless you  
> DECREF it explicitely, ob_refcnt should never be 0. (Also, the -> operator  
> exists for exactly this usage).
>
> >  PyList_SetItem(pArg, 0, pArgs);
> >  pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL);
>
> You didn't show us how you got pFunc here. Just to make it clear, you are  
> calling pFunc with a single argument, which is a list that contains a  
> single element, which is a tuple containing exactly MAX_ELEMENT float  
> objects.
>
> > Traceback
> >if x.ndim != 1; /*x is the input array, checking if it's a 1D*/
> > AttributeError: 'list' object has no attribute 'ndim'
>
> Python lists don't have a ndim attribute. Perhaps you want some kind of  
> Numeric array? (ndarray?)
>
> > I have been trying many call variations, but alas, I think the problem
> > lies in the list building process. I have no problems calling a non-
> > arrayed (albeit,still single) argument.
>
> Yes, it appears that you are building a plain list but your code is  
> expecting another kind of object. I'm unfamiliar with Numeric arrays, if  
> that is what you need; perhaps someone else can help, or ask again in a  
> Numeric-specific list.
>
> --
> Gabriel Genellina- Zitierten Text ausblenden -
>
> - Zitierten Text anzeigen -

yeah, i was looking at am array full of numbers. import numpy,scipy,
maybe pylab too while i was testing out the function over at a python
shell, make a linspace, sin it, and then call the function (which also
is from the scipy cookbook). Is numeric arrays (or ndarray) unlike
normal listing then? Since I started off programming in C, I am having
a bit of a confusion identifiying the different type of arrays,
listing and tuples and such... (since it's just "build an array of
type so and so, and pass it over" ^^;;)

the reason i didn't show pFunc is that because it is the result of
operations done to FuncName (ModName = module to be imported, FuncName
= function to be called), therefore i feel it would be a bit waste of
time/space to put in the pFunc function, since I didn't change the
operations concerning pFunc other than changing argv[1] to FuncName
from the link i gave (and not the core of my problem).

so yeah, maybe I am building and passing the array/calling the
function the wrong way... will have to take a look at numpy/numerical
specific C API and stuff now

thanks for your time and the help

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Embedding Python in C

2007-06-05 Thread mistabean
now then... where's the edit button...?

oh well, double-posting. Problem solved, thanks for pointing out that
I am needing a numeric array built instead of building a normal list/
tuple. For those who are curious, steps to solving:

...
#include "libnumarray.h" /*from numpy*/
...
...
...

void CallSnake(...)
{
...
...
Py_Initialize();
import_libnumarray(); /*badgered me to call this one... where i don't
know*/
...
...
pArray = NA_InputArray(pArgs, tFloat32, NUM_C_ARRAY); /*instead of
making a pArg and calling PyList_SetItem(pArg, 0, pArgs); */

/*Check for NULL on pArray*/

pValue = PyObject_CallFunctionObjArgs(pFunc,pArray,NULL);
/*error checking, cleaning up, Finalizing etc etc*/
}

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C

2007-06-05 Thread Joe Riopel
This seems like a pretty good resource, although I didn't read it all yet:
http://www.ibm.com/developerworks/edu/l-dw-linux-pythonscript-i.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python in C - newbie

2005-06-28 Thread Philippe C. Martin
Just to make sure i'm clear as I've been told about swig and pyrex: I don't
want to eventually have a python script call C modules, but rather a main.c
make calls to python functionnalities.

I did add newbie in the title :-)

Regards,

Philippe



Philippe C. Martin wrote:

> Hi,
> 
> Is there a program out there that would generate the C code to instantiate
> objects and call them:
> 
> ex: miracle.exe -i mymodule.py -o module_internface.c ?
> 
> I seem to recall a _yes_ to that but I got a memory overflow :-)
> 
> Thanks,
> 
> Philippe

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python in C - newbie

2005-06-28 Thread Philippe C. Martin
Sorry, it is still not clear when I reread it:

1) I have a bunch of Python working modules
2) I need to compile "something" so external C applications can access 1)

Thanks,

Philippe



Philippe C. Martin wrote:

> Just to make sure i'm clear as I've been told about swig and pyrex: I
> don't want to eventually have a python script call C modules, but rather a
> main.c make calls to python functionnalities.
> 
> I did add newbie in the title :-)
> 
> Regards,
> 
> Philippe
> 
> 
> 
> Philippe C. Martin wrote:
> 
>> Hi,
>> 
>> Is there a program out there that would generate the C code to
>> instantiate objects and call them:
>> 
>> ex: miracle.exe -i mymodule.py -o module_internface.c ?
>> 
>> I seem to recall a _yes_ to that but I got a memory overflow :-)
>> 
>> Thanks,
>> 
>> Philippe

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C/C++

2006-08-10 Thread kingcrustybun
We are still struggling with this but having spent many hours looking
at related code on the net, i have noticed the following sequence quite
a lot

globals = PyDict_New();
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());

Can anyone explain what this does exactly? I know what "__builtins__"
is from a Python perspective but cant understand why you would want to
add it to another newly created dictionary?

Also, where can i find info on PyEval_GetBuiltins().
It does not appear in the Release 2.4.3 Python/C API Reference index at
http://docs.python.org/api/genindex.html

In fact there are a whole lot of PyEval_??? items which do not appear
in this index.

Are these deprecated? If so what does on use now?

Any idea please?

-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in C, undefined symbol: PyExc_FloatingPointError

2005-08-16 Thread Simon Newton
Hi,

I've just starting out embedding Python in C and get the following error
when I try and import a module that in turn imports the math module.

ImportError: /usr/lib/python2.4/lib-dynload/math.so: undefined symbol:
PyExc_FloatingPointError

The module is as follows:

# begin script.py
import math

def fn(i):
print "i is %d" % i

# end script.py

and the C code is :

// start main.c
#include 

int main(int argc, char *argv[]) {
PyObject *mymod, *fn, *strargs;

Py_Initialize();

mymod = PyImport_ImportModule("script");

if(mymod == NULL) {
PyErr_Print();
exit(1);
}
  
fn = PyObject_GetAttrString(mymod, "fn");

if(fn == NULL) {
PyErr_Print();  
exit(1) ;
}

strargs = Py_BuildValue("(i)", 0);
PyEval_CallObject(fn, strargs);

Py_Finalize();
return 0;
}
// end main.c

Testing script.py by running python and importing the module works fine.
Commenting out the import math statement and import other modules (sys,
string etc) work fine.

The C program is being built like so:

gcc main.c -c -I-I/usr/include -I/usr/include -I/usr/include/python2.4
-I/usr/include/python2.4  -DNDEBUG -g -O3 -Wall -Wstrict-prototypes
gcc main.o -L/usr/lib  -lpthread -ldl  -lutil
-lm /usr/lib/python2.4/config/libpython2.4.a -o main

I've tried the above on two machines, one Debian stable and the other
Debian testing. Same results on both.

It's like I'm missing a library or something, any ideas ?

Cheers,

Simon Newton


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C, undefined symbol: PyExc_FloatingPointError

2005-08-17 Thread Martin v. Löwis
Simon Newton wrote:
> gcc main.c -c -I-I/usr/include -I/usr/include -I/usr/include/python2.4
> -I/usr/include/python2.4  -DNDEBUG -g -O3 -Wall -Wstrict-prototypes
> gcc main.o -L/usr/lib  -lpthread -ldl  -lutil
> -lm /usr/lib/python2.4/config/libpython2.4.a -o main
> 
> I've tried the above on two machines, one Debian stable and the other
> Debian testing. Same results on both.
> 
> It's like I'm missing a library or something, any ideas ?

No. You need to export the Python symbols from your executable to
extension modules. IOW, you need to pass

-Xlinker -export-dynamic

to the gcc invocation.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C, undefined symbol: PyExc_FloatingPointError

2005-08-17 Thread Simon Newton
On Wed, 2005-08-17 at 09:52 +0200, "Martin v. Löwis" wrote:
> Simon Newton wrote:
> > gcc main.c -c -I-I/usr/include -I/usr/include -I/usr/include/python2.4
> > -I/usr/include/python2.4  -DNDEBUG -g -O3 -Wall -Wstrict-prototypes
> > gcc main.o -L/usr/lib  -lpthread -ldl  -lutil
> > -lm /usr/lib/python2.4/config/libpython2.4.a -o main
> 
> No. You need to export the Python symbols from your executable to
> extension modules. IOW, you need to pass
> 
> -Xlinker -export-dynamic
> 
> to the gcc invocation.

Thanks Martin,

-export-dynamic fixed it.

Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python in C, undefined symbol: PyExc_FloatingPointError

2005-08-17 Thread en.karpachov
On Wed, 17 Aug 2005 14:29:43 +0800
Simon Newton wrote:

> The C program is being built like so:
> 
> gcc main.c -c -I-I/usr/include -I/usr/include -I/usr/include/python2.4
> -I/usr/include/python2.4  -DNDEBUG -g -O3 -Wall -Wstrict-prototypes
> gcc main.o -L/usr/lib  -lpthread -ldl  -lutil
> -lm /usr/lib/python2.4/config/libpython2.4.a -o main

Try to link libpython as a library (as it should be), not as an object
module:

gcc main.o -L/usr/lib  -lpthread -ldl  -lutil -lm -lpython2.4 -o main

-- 
jk
-- 
http://mail.python.org/mailman/listinfo/python-list


error on crude test of embedding python in c++ HELP PLEASE

2004-12-07 Thread Donnie Leen
I wrote a program to test calling c function from python code embedding in c
as following, it cause error after running a while(about 398 circle).  I
test it in msvc6, python2.3, windows 2k, could anyone tell me why this
happened since i just work according to the document? Thanks first.

Donnie Leen


source code:


#include 

static PyObject* pymyfun( PyObject* self, PyObject* args )
{
 return Py_None;// do nothing
}
static PyMethodDef emb_methods[] = {
{ "fun", pymyfun, METH_VARARGS, "doc." },
{NULL, NULL, 0, NULL}
};

void main(  )
{
Py_Initialize(  );

 PyObject* r = Py_InitModule( "mymodule", emb_methods );
 PyRun_SimpleString( "import mymodule" );
 while ( 1 )
 {
  // error occur after 398 loops here
  PyRun_SimpleString( "mymodule.fun( 'testest' )" );
 }

 Py_Finalize();
}



-- 
http://mail.python.org/mailman/listinfo/python-list


embedding python in C, working but with exception at the end

2005-09-03 Thread brobigi
well I manage to figure it out myself. I'm using Bloodshed Dev-cpp
Here's the code:


#include "python.h"
#include 

int main(int argc, char* argv[])
{
double answer = 0;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;

Py_Initialize();
modname = PyString_FromString("Test");
mod = PyImport_Import(modname);
if (mod)
{
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, "doit"); /* borrowed 
reference */
if (func)
{
if (PyCallable_Check(func))
{
stringarg = PyString_FromString("5");/*pay 
attention here*/
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, stringarg);
rslt = PyObject_CallObject(func, args);
if (rslt)
{
answer = PyFloat_AsDouble(rslt);
Py_XDECREF(rslt);
}
  Py_XDECREF(stringarg);
  Py_XDECREF(args);
}
}

Py_XDECREF(mod);
}

Py_XDECREF(modname);

Py_Finalize();

printf("%g",answer);

return 0;
}

I need to add include and lib directories to the project in order to
everything works fine. Also Test.py  is copied in Dev-cpp source code's
folder.
Test file contains the following code

def doit(x1):
try:
x2 = eval(x1)
except:
print 'Error!'
return 0

else:
return x2




However there is an error. Look at the line stringarg =
PyString_FromString("5"); If I put this:
stringarg = PyString_FromString("5+2"); or even this stringarg =
PyString_FromString("5.0");
Program crashes at line Py_Finalize(). Program tries to read some
memory location and suffer run time exception.
Only suggestion is to try to send it to Microsoft.
Why is this happening?
Everything (seems to) works fine I comment line Py_Finalize(), but I
know that this is not a real solution.

Does anybode have a clue what is happening?

Thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error on crude test of embedding python in c++ HELP PLEASE

2004-12-07 Thread Thomas Heller
"Donnie Leen" <[EMAIL PROTECTED]> writes:

> I wrote a program to test calling c function from python code embedding in c
> as following, it cause error after running a while(about 398 circle).  I
> test it in msvc6, python2.3, windows 2k, could anyone tell me why this
> happened since i just work according to the document? Thanks first.
>
> Donnie Leen
>
>
> source code:
>
>
> #include 
>
> static PyObject* pymyfun( PyObject* self, PyObject* args )
> {
>  return Py_None;// do nothing

You forgot an Py_INCREF here:
  Py_INCREF(Py_None);
  return Py_None;// do nothing

> }
> static PyMethodDef emb_methods[] = {
> { "fun", pymyfun, METH_VARARGS, "doc." },
> {NULL, NULL, 0, NULL}
> };
>
> void main(  )
> {
> Py_Initialize(  );
>
>  PyObject* r = Py_InitModule( "mymodule", emb_methods );
>  PyRun_SimpleString( "import mymodule" );
>  while ( 1 )
>  {
>   // error occur after 398 loops here
>   PyRun_SimpleString( "mymodule.fun( 'testest' )" );
>  }
>
>  Py_Finalize();
> }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error on crude test of embedding python in c++ HELP PLEASE

2004-12-07 Thread Donnie Leen
Got it, thanks :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Program crashes at line Py_Finalize(). Program tries to read some
>memory location and suffer run time exception.

PyTuple_SetItem "steals" a reference, so changing

Py_XDECREF(stringarg);
Py_XDECREF(args);

to just

Py_XDECREF(args);

might fix the problem.

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread jepler
I see a couple of problems.  First, because I'm using Unix, where filenames are
case-sensitive, I had to '#include "Python.h"' instead of '#include
"python.h"'.

Next, it looks like the behavior that '.' is placed on sys.path isn't done
automatically when embedding.  So I had to set the environment variable
"PYTHONPATH=." since Test.py was in the current directory.

Before I did this, I got this output:
Exception exceptions.ImportError: 'No module named Test' in 'garbage
collection' ignored
Fatal Python error: unexpected exception during garbage collection
Aborted
which was a clue about the problem you were running into.  This ImportError was
being caused back at PyImport_Import but was being transmuted into a fatal
error down at Py_Finalize().  By adding 'else { PyErr_Print(); }' to the end of
'if(mod)', I got the error message printed and cleared.  Now, garbage
collection which is kicked off by Py_Finalize() doesn't find the existing error
condition and treat it as a fatal error.

In your code, 'rslt' will be a Python Integer, not a Python Float, so
PyFloat_AsDouble will fail.  You could either write something like
if (rslt)
{   
if(PyFloat_Check(rslt)) {
answer = PyFloat_AsDouble(rslt);
} else {
printf("not a float\n");
answer = 1.0;
}
Py_XDECREF(rslt);
}
instead, or use PyErr_Check() + PyErr_Print() or PyErr_Clear().
If you want to accept integer or float returns, then maybe you want
if(PyFloat_Check(rslt)) { answer = PyFloat_AsDouble(rslt); }
else if(PyInt_Check(rslt)) { answer = PyInt_AsLong(rslt); }
else probably not a numeric type

Jeff


pgpsNcJ3ylwlJ.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list