从C编译器调用python函数

选择 | 换行 | 行号
  1. from ctypes import *
  2. class HELLO(Structure):
  3.     _fields_=[("a",c_int),
  4.               ("b",c_int)]
  5. x=input()
  6. y=input()
  7. hai=HELLO(x, y)
  8. print hai.a,hai.b

这是我在python中的代码.现在我可以从c编译器调用函数Hello(x,y),也可以在C编译器窗口中看到这段代码的输出...有没有可能...如果可能的话,请给出主意...

# 回答1


不可能.Ctype用于从Python中调用带有C类型参数的C库函数.
# 回答2


好的……有没有可能用c++包装器代码来编写结构?
例如,这是阶乘ok的c语言包装代码.

选择 | 换行 | 行号
  1. #include <Python.h>
  2.  
  3. int fact(int n)
  4. {
  5.     if ((n == 0)||(n==1))
  6.         return 1;
  7.     else
  8.         return fact(n*fact(n-1));
  9. }
  10.  
  11. static PyObject* fact(PyObject* self, PyObject* args)
  12. {
  13.     const char *command;
  14.     int n;
  15.  
  16.     if (!PyArg_ParseTuple(args, "i", &n))
  17.         return NULL;
  18.  
  19.     return Py_BuildValue("i", fact(n));
  20. }
  21.  
  22. static PyMethodDef FactMethods[] = {
  23.     {"fact", fact, METH_VARARGS, "Calculate the Factorial of given numbers."},
  24.     {NULL, NULL, 0, NULL}
  25. };
  26.  
  27. PyMODINIT_FUNC
  28. initfact(void)
  29. {
  30.     (void) Py_InitModule("fact", FactMethods);
  31. }

在这里,我可以使用Fact()函数调用......代替函数,有没有可能在这段代码中编写结构

# 回答3


看起来你走上了正确的道路.
你的C语言让我摸不着头脑,但我相信你想做的事情是可能的.
# 回答4


无论如何,谢谢你的回复……我不知道这是否可能……好的,谢谢爸爸

标签: python

添加新评论