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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章