python可以使用ctypes庫調用c++編譯的so庫函數
0x01 c/c++編譯為so庫文件
編譯C文件
gcc -o libpycallfoo.so -shared -fPIC rsa.c
編譯C++文件
g++ -o libcallfoo.so -shared -fPIC rsa.cpp
對於cpp文件需要用extern "C"{} 把main括起來 ,否則有可能報錯
1 extern "C"{ 2 int foo(int len,char *p,char* ret) 3 { 4 __int64 a1 = 0x36; 5 __int64 a2 = 0x100; 6 __int64 a3 = 0xb5547; 7 8 int j; 9 char xz[100]={}; 10 memcpy(xz,p,len); 11 printf("your input is %s,len xz=%d\n",xz,strlen(xz)); 12 13 int* pResult = new int[100];//密文 14 int i; 15 for(i = 0; i < strlen(xz); i++) 16 { 17 int result1 = rsa_mod(xz[i],0,0x101,0,0xb5547,0); 18 pResult[i] = swapEndian(result1); 19 //printf("0x%04X ",pResult[i]); 20 } 21 memcpy((char *)ret,(char *)pResult,4*strlen(xz)); 22 return 0; 23 } 24 }
0x02 ctypes調用so
入參使用ctypes.c_char_p創建,出參需要使用ctypes.create_string_buffer創建內存,否則so中的內存在用完就釋放了,無法傳出來
1 import ctypes 2 3 def callfoo(str_in): 4 #print 'input:\n%s' %str_in 5 #調用庫 6 input = ctypes.c_char_p() #對應c指針類型 char *p 7 input.value=str_in #字符串賦值 8 ll = ctypes.cdll.LoadLibrary 9 lib = ll("./libcallfoo.so") #調用so 10 p=ctypes.create_string_buffer(4*len(str_in)) #申請出參的內存大小 11 lib.foo(len(str_in), input, p) 12 print p.raw #出參的訪問方式 13