C Python類型互換


  從Python到C的轉換用PyArg_Parse*系列函數,int PyArg_ParseTuple():把Python傳過來的參數轉為C;int PyArg_ParseTupleAndKeywords()與PyArg_ParseTuple()作用相同,但是同時解析關鍵字參數;它們的用法跟C的sscanf函數很像,都接受一個字符串流,並根據一個指定的格式字符串進行解析,把結果放入到相應的指針所指的變量中去,它們的返回值為1表示解析成功,返回值為0表示失敗。

  從C到Python的轉換函數是PyObject* Py_BuildValue():把C的數據轉為Python的一個對象或一組對象,然后返回之;Py_BuildValue的用法跟sprintf很像,把所有的參數按格式字符串所指定的格式轉換成一個Python的對象。
        C與Python之間數據轉換的轉換代碼:

 

 1 #include "stdafx.h"
 2 #include "python.h"
 3 
 4 
 5 int _tmain(int argc, _TCHAR* argv[])
 6 {
 7     Py_Initialize();
 8 
 9     if (!Py_IsInitialized())
10     {
11         printf("initialization fail!");
12         return -1;
13     }
14 
15     PyRun_SimpleString("import sys");
16     PyRun_SimpleString("sys.path.append('./')");
17 
18     PyObject *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pArg = NULL, *result = NULL;
19 
20     pModule = PyImport_ImportModule("demo");    //引入模塊
21 
22     if (!pModule)
23     {
24         printf("import module fail!");
25         return -2;
26     }
27 
28     pDict = PyModule_GetDict(pModule); //獲取模塊字典屬性 //相當於Python模塊對象的__dict__ 屬性
29     if (!pDict)
30     {
31         printf("find dictionary fail!");
32         return -3;
33     }
34 
35     pFunc = PyDict_GetItemString(pDict, "add"); //從字典屬性中獲取函數
36     if (!pFunc || !PyCallable_Check(pFunc))
37     {
38         printf("find function fail!");
39         return -4;
40     }
41 
42     /*
43     // 參數進棧
44     *pArgs;
45     pArgs = PyTuple_New(2);
46 
47     PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
48     PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));
49     */
50 
51     pArg = Py_BuildValue("(i, i)", 1, 2); //參數類型轉換,傳遞兩個整型參數
52     result = PyEval_CallObject(pFunc, pArg); //調用函數,並得到python類型的返回值
53 
54     int sum;
55     PyArg_Parse(result, "i", &sum); //將python類型的返回值轉換為c/c++類型
56     printf("sum=%d\n", sum);
57 
58     PyRun_SimpleString("print 'hello world!' ");
59     
60     Py_DecRef(pModule);
61     Py_DecRef(pDict);
62     Py_DecRef(pFunc);
63     Py_DecRef(pArg);
64     Py_DecRef(result);
65     
66 
67     Py_Finalize();
68 
69     getchar();
70     return 0;
71 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM