如何互换Python和C变量

时间:2018-10-01 16:59:43

标签: python c

我想运行这段代码。

  1. 如何在PyRun_SimpleString中运行“ for”循环?
  2. 如何将b分配给python变量a,反之? 我用它来编译
  

gcc -I / usr / include / python2.7 ABC.c -lpython2.7 -lm -lutil -lpthread   -ld

我是Python新手。请帮我。

#include <Python.h> 
#include <stdlib.h>
#include <import.h>
#include <graminit.h>
#include <pythonrun.h>
int main(int argc, char *argv[]) 
{ 
  PyObject  *pValue;
  Py_Initialize();
  int b, c=10;
  printf("1+1:\n"); 
  PyRun_SimpleString("print 1+1"); 

  printf("Load sage \n"); 
  PyRun_SimpleString("from sage.all import *"); 

  PyRun_SimpleString("a=2"); 
  PyRun_SimpleString("print 'g', a");

  PyRun_SimpleString("A=[0]*10");
  PyRun_SimpleString("for i in range(10):\n A[i]=i\n"");
  b=int(a);

  Py_Finalize(); 

  return 0; 
}

我现在已经处理了“ for”循环。尽管“ d”是全局的,但这里出现错误。但是,如果我停止“ d = c”,则它运行良好。

#include <Python.h> 
#include <stdlib.h>
#include <import.h>
#include <graminit.h>
#include <pythonrun.h>

int main() 
{ 

 PyObject  *pValue, *c, *d;

  Py_Initialize();
  long *b;
  printf("1+1:\n"); 
  PyRun_SimpleString("print 1+1"); 


  printf("Load sage \n"); 
  PyRun_SimpleString("from sage.all import *"); 

  PyRun_SimpleString("pValue=2");
  PyRun_SimpleString("print 'g', pValue");
  PyRun_SimpleString("A=[0]*10");
  PyRun_SimpleString("for i in range(10):\n"
                     "  A[i]=i*i\n");

  PyRun_SimpleString("print 'g', A[6]");
  d = PyInt_FromLong(40);
  PyRun_SimpleString("c=pValue+1");
  PyRun_SimpleString("print 'c', c");
  d=c;

  printf("Returned val: %ld\n", PyInt_AsLong(d));
  Py_Finalize(); 

  return 0; 
} 

0 个答案:

没有答案