Python調用動態庫函數返回字符串

系統環境

Centos 6.10 64位

Python:3.6.8

庫函數源碼

//add.cpp
#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

extern "C"
char* addchar(char* in){
	char ret[64]={0};
	strcat(ret, "in so");
	strcat(ret, in);
	return ret;
}

extern "C"
bool addf(char* in, char* out){
	printf("in:%x;out:%x\n", in, out);
	strcat(out, "in so");
	strcat(out, in);
	return true;
}

int main(){
	// printf("%d+%d=%d\n", 10, 20, addf(10, 20));
	char input[]="NLP";
	char output[128]={0};
	printf("%s\n", addchar(input));
	addf(input, output);
	printf("addf:%s\n", output);
}

編譯動態庫

g++ add.cpp -o add.so -fPIC -shared

Python調用庫函數

#test.py
from ctypes import *

# adddll = cdll.LoadLibrary('/root/Projects/test/add.so')
# adddll.addchar.argtypes = [c_char_p]
# adddll.addchar.restype = c_char_p
# addres = adddll.addchar(b"NLP")
# print(addres.decode("utf8"))

addres = create_string_buffer(512, "\0")#創建512字節內存塊,存放動態庫函數接口結果
adddll = cdll.LoadLibrary('/root/Projects/test/add.so')
adddll.addf.argtypes = [c_char_p, c_char_p]#so庫addf函數參數類型
try:
    adddll.addf(b"NLP", addres)
except Exception as e:
    print(str(e))

print(addres.value.decode("utf8"))

執行Python

python3 test.py

  

發佈了5 篇原創文章 · 獲贊 0 · 訪問量 3464
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章