1. 程式人生 > >ctypes 載入的so庫中函式引數的字串傳遞問題(str與bytes轉換)

ctypes 載入的so庫中函式引數的字串傳遞問題(str與bytes轉換)

在專案開發過程中,需要python使用ctypes 載入編譯好的so庫,然後呼叫so庫的函式,python傳入str引數,但是按通常python傳入字串引數的方法(func(“test”))時,so庫中的函式不能接收到全部的字串,而是隻能接受第一個字元,這樣顯然不能達到呼叫的目的。

如何才能讓完整的字串傳入到so庫中的函式中呢?那就需要把str型別的引數轉換成bytes型別才能夠傳入。

示例如下:

foo.c

#include <stdio.h>  
char* myprint(char *str)  
{  
    puts(str);  
    return str;  
} 

然後把 foo.c編譯成so

# gcc -fPIC -shared -o foo.so foo.c

foo.py

from ctypes import *    
  
foo = CDLL('./foo.so')    
  
str_test="need_bytes"  
  
foo.myprint(str_test) # 輸出結果:n  
  
utf8=str_test.encode()  
  
foo.myprint(utf8)  #輸出結果為:need_bytes  

如果傳入的引數是常量的話可以簡化轉換過程:foo.myprint(b"need_bytes")