C與Python相互調用函數時,函數間的參數傳遞需要進行轉換。近幾天試了下C++Builder調用Python的函數,也記一下來方便以後查。
1、C數據到Python數據轉
從C數據類型轉成Python數據類型可以使用Py_BuildValue()函數。
Return value: New reference
format為轉換格式說明字符串。
寫幾個常用的格式,具體的就不從python的說明文件拷貝過來了,用Py_BuildValue關鍵字可以找到相應說明。
"s" (string) [char *]
"z" (string or
將以null結尾的C字符串string轉換為Python對象,如果字符串為空則返回None。
"u" (Unicode string) [Py_UNICODE *]
Unicode(UCS-2或UCS-4)字符串轉為Python Unicode對象,如果字符串為空則返回None。
"i" (integer) [int]
"b" (integer) [char]
"h" (integer) [short int]
"l" (integer) [long int]
"B" (integer) [unsigned char]
"H" (integer) [unsigned short int]
將方括號[]相應的C類型轉為Python的integer數據對象
"I" (integer/long) [unsigned int]
"k" (integer/long) [unsigned long]
如果轉換的數字大於Python sys.maxint則轉為long integer否則轉為integer數據對象。
"d" (float) [double]
"f" (float) [float]
將C的double/float數據轉為Python的floating point數據對象
"(items)" (tuple) [matching-items]
"[items]" (list) [matching-items]
"{items}" (dictionary) [matching-items]
將多個相應的項目分別轉為tuple、list和dict數據對象。
PyObject* pString = Py_BuildValue("s","Python");
PyObject* pInt = Py_BuildValue("i", 2003);
2、Python數據轉成C數據
和前面的Py_BuildValue函數對著干,將Python的數據類型轉成C的數據,使用下面的函數。
args也就是需要轉換的Python數據對象。
format的格式定義和Py_BuildValue函數一樣。
int n;
const char *pstr;
PyArg_Parse(pyResult,"i",&n);
PyArg_Parse(pyResult,"s",&pstr);
另外,也可以用相應類型的轉換
char* PyString_AsString(PyObject *string) 轉換字符串
double PyFloat_AsDouble(PyObject *pyfloat) 轉換浮點數
long PyInt_AsLong( PyObject *io) 轉換為整數
這種方法可能會有問題,也可能只是我電腦或使用方法的問題。
1、C數據到Python數據轉
從C數據類型轉成Python數據類型可以使用Py_BuildValue()函數。
PyObject* Py_BuildValue( | const char *format, ...) |
format為轉換格式說明字符串。
寫幾個常用的格式,具體的就不從python的說明文件拷貝過來了,用Py_BuildValue關鍵字可以找到相應說明。
"s" (string) [char *]
"z" (string or
None
) [char *] 將以null結尾的C字符串string轉換為Python對象,如果字符串為空則返回None。
"u" (Unicode string) [Py_UNICODE *]
Unicode(UCS-2或UCS-4)字符串轉為Python Unicode對象,如果字符串為空則返回None。
"i" (integer) [int]
"b" (integer) [char]
"h" (integer) [short int]
"l" (integer) [long int]
"B" (integer) [unsigned char]
"H" (integer) [unsigned short int]
將方括號[]相應的C類型轉為Python的integer數據對象
"I" (integer/long) [unsigned int]
"k" (integer/long) [unsigned long]
如果轉換的數字大於Python sys.maxint則轉為long integer否則轉為integer數據對象。
"d" (float) [double]
"f" (float) [float]
將C的double/float數據轉為Python的floating point數據對象
"(items)" (tuple) [matching-items]
"[items]" (list) [matching-items]
"{items}" (dictionary) [matching-items]
將多個相應的項目分別轉為tuple、list和dict數據對象。
PyObject* pString = Py_BuildValue("s","Python");
PyObject* pInt = Py_BuildValue("i", 2003);
2、Python數據轉成C數據
和前面的Py_BuildValue函數對著干,將Python的數據類型轉成C的數據,使用下面的函數。
int PyArg_Parse( | PyObject *args, const char *format, ...) |
args也就是需要轉換的Python數據對象。
format的格式定義和Py_BuildValue函數一樣。
int n;
const char *pstr;
PyArg_Parse(pyResult,"i",&n);
PyArg_Parse(pyResult,"s",&pstr);
另外,也可以用相應類型的轉換
char* PyString_AsString(PyObject *string) 轉換字符串
double PyFloat_AsDouble(PyObject *pyfloat) 轉換浮點數
long PyInt_AsLong( PyObject *io) 轉換為整數
這種方法可能會有問題,也可能只是我電腦或使用方法的問題。