C/C++調用Python的數據類型轉換

本文介绍了C与Python间函数调用时的数据类型转换方法。利用Py_BuildValue将C数据转为Python对象,反之则通过PyArg_Parse实现。此外还提供了字符串、浮点数及整数等类型的直接转换函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 C與Python相互調用函數時,函數間的參數傳遞需要進行轉換。近幾天試了下C++Builder調用Python的函數,也記一下來方便以後查。

1、C數據到Python數據轉
從C數據類型轉成Python數據類型可以使用Py_BuildValue()函數。

PyObject* Py_BuildValue(const char *format, ...)
Return value: New reference

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) 轉換為整數

這種方法可能會有問題,也可能只是我電腦或使用方法的問題。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值