ctypes 數據類型和 C數據類型 對照表
ctypes type | C type | Python type |
---|---|---|
c_bool | _Bool | bool (1) |
c_char | char | 1-character string |
c_wchar | wchar_t | 1-character unicode string |
c_byte | char | int/long |
c_ubyte | unsigned char | int/long |
c_short | short | int/long |
c_ushort | unsigned short | int/long |
c_int | int | int/long |
c_uint | unsigned int | int/long |
c_long | long | int/long |
c_ulong | unsigned long | int/long |
c_longlong | __int64 or long long | int/long |
c_ulonglong | unsigned __int64 or unsigned long long | int/long |
c_float | float | float |
c_double | double | float |
c_longdouble | long double | float |
c_char_p | char * (NUL terminated) | string or None |
c_wchar_p | wchar_t * (NUL terminated) | unicode or None |
c_void_p | void * | int/long or None
|
//C++文件
#include<iostream> using namespace std; //該文件名稱:cpptest.cpp //終端下編譯指令: //g++ -o cpptest.so -shared -fPIC cpptest.cpp //-o 指定生成的文件名,-shared 指定微共享庫,-fPIC 表明使用地址無關代碼 extern "C"{//在extern “C”中的函數才能被外部調用 int test(int int_test,char char_test,char *test_string,int int_arr[4],char char_arr2[2][2]) { cout<<"輸出參數中的int型:"; cout<<int_test<<endl;
cout<<"輸出參數中的char型:"; cout<<char_test<<endl;
cout << "輸出參數中的字char*字符:"; cout<<test_string<<endl; cout << "輸出參數中的int數組"; for(int x = 0;x< 4;x++){cout << int_arr[x]<<" ";} cout << endl; cout <<"輸出參數中的二維數組:"; for(int x = 0;x<2;x++){ for(int y = 0;y<2;y++){ cout <<char_arr2[x][y] << " "; } } cout << endl; return 0; } }
//py文件
import ctypes mylib = ctypes.cdll.LoadLibrary("cpptest.so") char_p_test = bytes("中國","utf8")#漢字需用采用utf8編碼 int_arr4 = ctypes.c_int*4 int_arr = int_arr4() int_arr[0] = 1 int_arr[1] = 3 int_arr[2] = 5 int_arr[3] = 9 char_arr2 = ctypes.c_char*2 char_arr22 = char_arr2*2 char_arr22a = char_arr22() char_arr22a[0][0] = b'a' char_arr22a[0][1]= b'b' char_arr22a[1][0] = b'c' char_arr22a[1][1] = b'd' mylib.test(9999,'a',char_p_test,int_arr,char_arr22a)
參考:python 調用C++,傳遞int,char,char*,數組和多維數組
結構體傳參
https://www.jb51.net/article/52513.htm
『Python CoolBook』使用ctypes訪問C代碼_下_demo進階
https://www.programcreek.com/python/example/1243/ctypes.c_char_p