Sample Code for calling Python functions in C

Source: Internet
Author: User

When using the C language, we sometimes encounter the need to call Python functions to complete some specific functions. Next, we will introduce in detail how C calls Python functions and hope to help you.

Python script, saved as pytest. py

 
 
  1. def add(a,b):  
  2. print "in python function add"  
  3. print "a = " + str(a)  
  4. print "b = " + str(b)  
  5. print "ret = " + str(a+b)  
  6. return a + b 

Example code for C to call a Python function:

 
 
  1. # Include <stdio. h>
  2. # Include <stdlib. h>
  3. # Include "C:/Python26/include/python. h"
  4. # Pragma comment (lib, "C :\\ Python26 \ libs \ python26.lib ")
  5. Int main (int argc, char ** argv)
  6. {
  7. // Initialize Python
  8. // Before using the Python system, you must use Py_Initialize
  9. // Perform initialization. It loads Python built-in modules and adds the system path.
  10. // Path to the module search path. This function has no return value. Check the system
  11. // Use Py_IsInitialized to check whether the initialization is successful.
  12. PyObject * pName, * pModule, * pDict, * pFunc, * pArgs, * pRetVal;
  13. Py_Initialize ();
  14. // Check whether Initialization is successful
  15. If (! Py_IsInitialized ())
  16. {
  17. Return-1;
  18. }
  19. // Load the script named pytest (Note: It is not pytest. py)
  20. PName = PyString_FromString ("pytest ");
  21. PModule = PyImport_Import (pName );
  22. If (! PModule)
  23. {
  24. Printf ("can't find pytest. py ");
  25. Getchar ();
  26. Return-1;
  27. }
  28. PDict = PyModule_GetDict (pModule );
  29. If (! PDict)
  30. {
  31. Return-1;
  32. }
  33. // Find the function named add
  34. PFunc = PyDict_GetItemString (pDict, "add ");
  35. If (! PFunc |! PyCallable_Check (pFunc ))
  36. {
  37. Printf ("can't find function [add]");
  38. Getchar ();
  39. Return-1;
  40. }
  41. // Stack parameters
  42. PArgs = PyTuple_New (2 );
  43. // PyObject * Py_BuildValue (char * format ,...)
  44. // Convert the C ++ variable into a Python object. When you need
  45. // This function is used when C ++ passes a variable to Python. This function
  46. // A bit similar to C's printf, but the format is different. Common formats include:
  47. // S indicates a string,
  48. // I indicates an integer variable,
  49. // F indicates a floating point number,
  50. // O indicates a Python object.
  51. PyTuple_SetItem (pArgs, 0, Py_BuildValue ("l", 3 ));
  52. PyTuple_SetItem (pArgs, 1, Py_BuildValue ("l", 4 ));
  53. // Call the Python Function
  54. PRetVal = PyObject_CallObject (pFunc, pArgs );
  55. Printf ("function return value: % ld \ r \ n", PyInt_AsLong (pRetVal ));
  56. Py_DECREF (pName );
  57. Py_DECREF (pArgs );
  58. Py_DECREF (pModule );
  59. Py_DECREF (pRetVal );
  60. // Close Python
  61. Py_Finalize ();
  62. Return 0;
  63. }
  64. // Another method for personal practice
  65. # Include <Python. h>
  66. # Include <conio. h>
  67. Int main ()
  68. {
  69. Py_Initialize ();
  70. If (! Py_IsInitialized ())
  71. {
  72. Printf ("initialization error \ n ");
  73. Return-1;
  74. }
  75. PyObject * pModule = NULL;
  76. PyObject * pFunc = NULL;
  77. PyObject * pArg = NULL;
  78. PyObject * pRetVal = NULL;
  79. PModule = PyImport_ImportModule ("hello ");
  80. PFunc = PyObject_GetAttrString (pModule, "hello ");
  81. PArg = Py_BuildValue ("(I, I)", 33,44 );
  82. PRetVal = PyObject_CallObject (pFunc, pArg );
  83. Printf ("% d \ n", PyInt_AsLong (pRetVal ));
  84. Py_Finalize ();
  85. _ Getch ();
  86. Return 0;
  87. }

The above is an introduction to the operation methods related to calling Python functions in C.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.