How to embed?

Ignacio Vazquez-Abrams ignacio at openservices.net
Sat Sep 8 13:53:51 EDT 2001


On Sat, 8 Sep 2001, vin wrote:

> OK here is my question.
>
> I have a file that contains a definition of a function
>
> #exmpl.py
>
> def foo(x,y):
>         return x+y
>
>
> Now, I want to embed Python in a C program.  After calling Py_Initialize():
> I can call  PyRun_SimpleString("import exmpl\n"); to import my function.
> Now suppose that in my C program I have statements
>
> double X,Y, result_in_c;
> X=5.5; Y=6.6;
>
> How do I pass X and Y to foo and get the output from foo to result_in_c so
> that I can process this output further in my C program?
>
> Thanks
> Vin

How about this:

---
#include <stdio.h>
#include <Python.h>

int main(void)
{
  PyObject *module, *dict, *foo, *result;
  double x=5.5, y=6.6;

  Py_Initialize();

  module=PyImport_ImportModule("exmpl");
  dict=PyModule_GetDict(module);
  foo=PyDict_GetItemString("foo");
  result=PyObject_CallFunction(foo, "dd", x, y);
  printf("The answer is %.2f!\n", PyFloat_AsDouble(result));

  Py_Finalize();

  return 0;
};
---

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>






More information about the Python-list mailing list